<?php

namespace app\admin\service;

use app\model\Link;
use app\model\OperateLog;
use app\model\PayRecord;
use app\model\RechargeTemplate;
use app\model\User;
use app\model\VideoDetails;
use think\facade\Cache;
use think\facade\Db;
use app\common\Common;
use app\model\DeliveryData;
use app\model\Videos;
use app\model\ResponsibilityPerson;
use app\model\LaunchAccount;
use app\model\DailyDeliveryData;
use app\model\Company;
use app\model\OfficialAccounts;
use app\model\CustomRechargeTemplate;
use app\model\EchoRuleConfig;
use app\model\Subject;

class LaunchService
{
    private $model;
    private $payRecordModel;
    private $userModel;
    private $deliveryDataModel;
    private $videosModel;
    private $responsibilityPersonModel;
    private $launchAccountModel;
    private $dailyDeliveryDataModel;
    private $companyModel;
    private $operateLogModel;
    private $officialAccountModel;
    private $echoRuleConfigModel;
    private $subjectModel;

    public function __construct(Link $model, PayRecord $payRecordModel, User $userModel, DeliveryData $deliveryDataModel, Videos $videosModel, ResponsibilityPerson $responsibilityPersonModel, LaunchAccount $launchAccountModel, DailyDeliveryData $dailyDeliveryDataModel, Company $companyModel, OperateLog $operateLogModel, OfficialAccounts $officialAccountModel, EchoRuleConfig $echoRuleConfigModel, Subject $subjectModel)
    {
        $this->model = $model;
        $this->payRecordModel = $payRecordModel;
        $this->userModel = $userModel;
        $this->deliveryDataModel = $deliveryDataModel;
        $this->videosModel = $videosModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->launchAccountModel = $launchAccountModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
        $this->companyModel = $companyModel;
        $this->operateLogModel = $operateLogModel;
        $this->officialAccountModel = $officialAccountModel;
        $this->echoRuleConfigModel = $echoRuleConfigModel;
        $this->subjectModel = $subjectModel;
    }

    /**
     * 获取投放总览统计数据
     *
     * @return array
     * @author zhixiang0215@126.com
     */
    public function getOverviewDataStatistics()
    {
        // 累计充值/累计成本
        $deliveryData = $this->deliveryDataModel->getDataByWhere([], 'total_recharge, total_cost, register_user_num, activation_user_num, actual_cost');
        $totalRecharge = array_sum(array_column($deliveryData, 'total_recharge'));
        $totalSpend = array_sum(array_column($deliveryData, 'actual_cost'));

        // 当月充值
        $startDate = date('Ym', time()) . '01';
        $endDate = date('Ymt', time());
        $thisMonthRecharge = $this->deliveryDataModel->where([['date', '>=', $startDate], ['date', '<=', $endDate]])->sum('total_recharge');

        // 上月充值
        $startDate = date('Ym', strtotime('-1 month')) . '01';
        $endDate = date('Ymt', strtotime(-date('d') . 'day'));
        $lastMonthRecharge = $this->deliveryDataModel->where([['date', '>=', $startDate], ['date', '<=', $endDate]])->sum('total_recharge');

        // 总关注用户
        $totalUser = array_sum(array_column($deliveryData, 'register_user_num'));

        $data = [
            'total_recharge' => round($totalRecharge, 2),
            'this_month_recharge' => round($thisMonthRecharge, 2),
            'last_month_recharge' => round($lastMonthRecharge, 2),
            'total_user' => $totalUser,
            'total_spend' => round($totalSpend, 2)
        ];

        return $data;
    }

    // 获取抖音今日实时在投数据
    public function getInvestingData($params)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        $where[] = ['media_id', '=', 1];
        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }

        // 公司搜索
        if (!empty($params['company_id'])) {
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $key1 = config('redis_key.real_time_investment_create_time') . date('Ymd');
        $key2 = config('redis_key.real_time_investment_total_click_num') . date('Ymd');
        $key3 = config('redis_key.real_time_investment_total_new_user') . date('Ymd');

        // 取缓存数据
        if ($timeStamp = $redis->get($key1)) {
            $totalClickNum = $redis->get($key2);
            $totalNewUserCount = $redis->get($key3);
            $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
            if ($data) {
                return [
                    'create_time' => date('Y-m-d H:i:s', $timeStamp),
                    'total_click_num' => $totalClickNum,
                    'total_new_user' => $totalNewUserCount,
                    'data' => $data
                ];
            }
        }

        // 分销商链接不查询
        $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['pid' => Db::raw('IS NOT NULL')], 'id');
        $distributorResponsibilityPersonIds = array_column($distributorResponsibilityPerson, 'id');
        $linkData = $this->model->getDataByWhere([['media_id', '=', 1], ['link_switch', '=', 1], ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds]], 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id,link_type');

        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);

        $appId1 = config('tiktok.huge_amount_yaodao.app_id');
        $secret1 = config('tiktok.huge_amount_yaodao.secret');
        $accessToken1 = Common::getHugeAmountAccessToken($appId1, $secret1);

        $appId24 = config('tiktok.huge_amount_xingcan.app_id');
        $secret24 = config('tiktok.huge_amount_xingcan.secret');
        $accessToken24 = Common::getHugeAmountAccessToken($appId24, $secret24);

        // $appId5 = config('tiktok.huge_amount_sixseals_erfen.app_id');
        // $secret5 = config('tiktok.huge_amount_sixseals_erfen.secret');
        // $accessToken5 = Common::getHugeAmountAccessToken($appId5, $secret5);

        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];
        // $url = 'https://ad.oceanengine.com/open_api/2/report/campaign/get/';
        $url = 'https://api.oceanengine.com/open_api/v3.0/project/list/';
        $url2 = 'https://api.oceanengine.com/open_api/v3.0/report/custom/get/';

        $totalClickNum = $totalNewUserCount = 0;

        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            if ($value['subject_id'] == 8) {
                $hearder['headers'] = ['Access-Token:' . $accessToken1];
            } elseif ($value['subject_id'] == 24) {
                $hearder['headers'] = ['Access-Token:' . $accessToken24];
            } else {
                $hearder['headers'] = ['Access-Token:' . $accessToken];
            }

            // 获取成本
            $getProjectBody = [
                'advertiser_id' => intval($value['advertiser_id']),
                'fields' => ['project_id'],
                'page_size' => 100
            ];

            $getProjectRequestData = [];
            foreach ($getProjectBody as $k1 => $val1) {
                $getProjectRequestData[$k1] = is_string($val1) ? $val1 : json_encode($val1);
            }

            $getProjectResult = Common::_curl($url, $getProjectRequestData, 'GET', $hearder);
            $getProjectResult = json_decode($getProjectResult, true);

            if ($getProjectResult['code'] != 0) {
                return ['message' => $getProjectResult['message'] . '；link_id：' . $value['id']];
            }

            if (empty($getProjectResult['data']['list'])) {
                // $responsibilityPersonResult = $this->responsibilityPersonModel->getInfoById($value['responsibility_person_id'], 'name');
                // return ['message' => '链接ID：'.$value['id'].'（所属投放：'.$responsibilityPersonResult['name'].'） 没有在投放的项目，请关闭投放开关'];
                continue;
            }

            $string = '';
            foreach ($getProjectResult['data']['list'] as $val2) {
                $string .= $val2['project_id'] . ',';
            }
            $projectIdString = substr($string, 0, -1);
            $projectId = explode(',', $projectIdString);
            if (!empty($projectId)) $this->model->edit(['id' => $value['id'], 'project_id' => $projectIdString]);

            $body = [
                'dimensions' => ['stat_time_day', 'cdp_project_name'],
                'advertiser_id' => $value['advertiser_id'], // 广告账户id
                'start_time' => $startDate,
                'end_time' => $endDate,
                'metrics' => ['stat_cost'],
                'order_by' => [
                    [
                        'field' => 'stat_time_day',
                        'type' => 'DESC'
                    ]
                ],
                'filters' => [
                    [
                        'field' => 'cdp_project_id',
                        'type' => 3,
                        'operator' => 1,
                        'values' => $projectId // 项目id
                    ]
                ]
            ];

            $requestData = [];
            foreach ($body as $k => $val) {
                $requestData[$k] = is_string($val) ? $val : json_encode($val);
            }

            $result = Common::_curl($url2, $requestData, 'GET', $hearder);
            $result = json_decode($result, true);

            if (!$result['code']) {

                $value['cost'] = 0;
                // if (!empty($result['data']['rows'])) {
                //     foreach ($result['data']['rows'] as $key => $item) {
                //         $value['cost'] += $item['metrics']['stat_cost'];
                //     }
                // }
                if (!empty($result['data']['total_metrics'])) {
                    $value['cost'] = $result['data']['total_metrics']['stat_cost'];
                }

                $data[] = $value;
            } else {
                return ['message' => $result['message'] . '；link_id：' . $value['id']];
            }

            $accountIds[] = trim($value['advertiser_id']);
            $responsibilityPersonIds[] = $value['responsibility_person_id'];
        }

        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time');

            $newUserPayData = $rechargeNumber = $newUserNum = [];

            if ($userInfo) {
                $newUids = array_column($userInfo, 'id');
                $totalNewUserCount = count($newUids);
                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $userData = array_count_values($links);
            }

            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                }

                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点数据
            $launchAccountData = $this->launchAccountModel->getDataByWhere(['account_id' => $accountIds], 'account_id, rebate');
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-12 当期充值95折扣
                $tmp_discount_data = bcmul($currentRecharge, 0.95, 3); // 当前充值的95折扣
                $data[$key]['current_recharge_discount'] = round($tmp_discount_data, 2);
                // end

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRecharge / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;
                $data[$key]['conversion_cost'] = $conversionNumber == 0 ? 0 : round($item['cost'] / $conversionNumber, 2); // 转化成本

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;

                // 转化率
                $data[$key]['conversion_rate'] = !empty($userData[$item['id']]) ? round($newUserNumber / $userData[$item['id']] * 100, 2) . '%' : '0%';
                $totalClickNum += empty($userData[$item['id']]) ? 0 : $userData[$item['id']];

                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($item['cost'] / $userData[$item['id']]) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge; // 当天累计充值暂时等于当期充值

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['media_id'] = 1; // 抖音

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } else if (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                unset($data[$key]['rebate']);
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = $tmp_actual_cost = round($actualCost, 2);

                // by huangxiaoshan 2023-07-12 新增95折净利润
                $profit = bcsub($tmp_discount_data, $tmp_actual_cost);

                $data[$key]['current_recharge_profit'] = round($profit, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况

                unset($data[$key]['subject_id']);
            }
        }

        Db::name('real_time_data_cache')->where(['media_id' => 1])->delete(true);
        $bool = Db::name('real_time_data_cache')->insertAll($data);
        if ($bool) {
            $redis->set($key1, time(), 15 * 60); // 数据产生的时间
            $redis->set($key2, $totalClickNum, 15 * 60);
            $redis->set($key3, $totalNewUserCount, 15 * 60);
        }

        $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data
        ];

        return $result;
    }

    // 获取抖音今日实时在投数据
    public function getTiktokInvestingData($params)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        $where[] = ['media_id', '=', 1];
        $where[] = ['link_switch', '=', 1];

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 账户id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }

        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }

        // 公司搜索
        if (!empty($params['company_id'])) {
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        }

        // 分销商链接不查询
        // $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['pid' => Db::raw('IS NOT NULL'), 'is_distributor' => 1], 'id');
        // $distributorResponsibilityPersonIds = array_column($distributorResponsibilityPerson, 'id');
        // $where[] = ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds];

        // 分销商链接不查询
        $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id');
        $distributorResponsibilityPersonPids = array_column($distributorResponsibilityPerson, 'id');

        $distributorPitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $distributorResponsibilityPersonPids], 'id, pid');
        $distributorResponsibilityPersonIds = array_column($distributorPitcher, 'id');

        $where[] = ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds];
        $linkData = $this->model->getDataByWhere($where, 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id, created_at, is_new_back_setting, echo_rule_config_id,link_type');

        $startDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];

        $totalClickNum = $totalNewUserCount = 0;

        // 获取redis花费数据
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        // 
        $redisCostData = [];
        $redisCostData1 = $redis->get('oceanengine_business_ad_data_today:18006505024'); // 杭州泉起抖小
        $redisCostData2 = $redis->get('oceanengine_business_ad_data_today:sybyn6'); // 杭州泉起
        $redisCostData3 = $redis->get('oceanengine_business_ad_data_today:sybyn1'); // 泉起-抖小-艺达

        $redisCostDataLiuYi = json_decode($redisCostData1, true);
        $redisCostDataGuangZhou = json_decode($redisCostData2, true);
        $redisCostDataThree= json_decode($redisCostData3, true);
        if (!empty($redisCostDataLiuYi['data'])) {
            $redisCostData = $redisCostData + $redisCostDataLiuYi['data'];
        }
        if (!empty($redisCostDataGuangZhou['data'])) {
            $redisCostData = $redisCostData + $redisCostDataGuangZhou['data'];
        }
        if (!empty($redisCostDataThree['data'])) {
            $redisCostData = $redisCostData + $redisCostDataThree['data'];
        }
        
        if (empty($redisCostData)) {
            $redisCostData = $redis->get(config('redis_key.tiktok_real_time_cost') . date('Ymd'));
            $redisCostData = json_decode($redisCostData, true);
            $syncTimeLiuYi = $syncTimeGuangZhou = date('Y-m-d H:i:s');
        } else {
            $syncTimeLiuYi = $redisCostDataLiuYi['sync_time'];
            $syncTimeGuangZhou = $redisCostDataGuangZhou['sync_time'];
        }

        $linkIds = $advertiserIds = $newBackLinkIds = [];
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            // 花费
            $value['cost'] = !empty($redisCostData[$value['advertiser_id']]['stat_cost']) ? $redisCostData[$value['advertiser_id']]['stat_cost'] : 0;
            // 账户余额
            $value['balance'] = !empty($redisCostData[$value['advertiser_id']]['advertiser_balance']) ? $redisCostData[$value['advertiser_id']]['advertiser_balance'] : 0;
            $data[] = $value;
            $responsibilityPersonIds[] = $value['responsibility_person_id'];

            // 获取后台打开投放开关的投放账户
            unset($redisCostData[$value['advertiser_id']]);

            if ($value['is_new_back_setting'] == 2) {
                $newBackLinkIds[] = $value['echo_rule_config_id'];
                $newBackLink[$value['id']] = $value['echo_rule_config_id'];
            }
        }

        // 开启已关闭投放的链接
        if (!empty($redisCostData) && empty($params)) {
            foreach ($redisCostData as $advertiserId => $cost) {
                $link = Db::name('link')->where(['advertiser_id' => $advertiserId])->order('id desc')->field('id')->find();
                Db::name('link')->where(['id' => $link['id']])->update(['link_switch' => 1]);
            }
        }

        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id , type , uid, total_fee, activation_time, pay_merchant');

            $newUserPayData = $rechargeNumber = $newUserNum = $newActivityPayData = $tencentPayData = [];

            if ($userInfo) {
                $newUids = array_column($userInfo, 'id');
                $totalNewUserCount = count($newUids);
                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $userData = array_count_values($links);
            }

            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['type'] == config('enum.activity_pay_type', 13)) {
                        $newActivityPayData[$value['link_id']][] = $value['total_fee'];
                    }
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            // 获取新回传数据
            if ($newBackLinkIds) {
                $newBackData = $this->echoRuleConfigModel->getDataByWhere(['id' => $newBackLinkIds], 'id, back_rate_type, echo_rate, pass, leak');
                $newBack = array_column($newBackData, NULL, 'id');
            }

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                $activityRecharge = empty($newActivityPayData[$item['id']]) ? 0 : array_sum($newActivityPayData[$item['id']]);
                $data[$key]['activity_recharge'] = round($activityRecharge, 2); // 活动充值

                // by huangxiaoshan 2023-07-12 当期充值95折扣
                $tencentTenPercent = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;

                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRechargeDiscount / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;

                // 转化率
                $data[$key]['conversion_rate'] = !empty($userData[$item['id']]) ? round($newUserNumber / $userData[$item['id']] * 100, 2) . '%' : '0%';
                $totalClickNum += empty($userData[$item['id']]) ? 0 : $userData[$item['id']];

                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge; // 当天累计充值暂时等于当期充值

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['media_id'] = 1; // 抖音

                // 实际花费
                $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);

                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($actualCost / $newUserNumber, 2); // 转化成本
                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($actualCost / $userData[$item['id']], 2) : 0; // 粉丝成本
                unset($data[$key]['rebate']);

                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRechargeDiscount / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-12 新增95折净利润
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况

                // by huangxiaoshan 2023-07-24 人均订单数.
                $data[$key]['avg_person_order'] = 0;
                if ($newRechargeNumber && $newUserNumber) {
                    $data[$key]['avg_person_order'] = round(bcdiv((string)$newRechargeNumber, (string)$newUserNumber, 3), 2);
                }
                // end
                unset($data[$key]['subject_id']);
                // 获取新回传规则的回传率
                if ($item['is_new_back_setting'] == 2) {
                    $newBackInfo = !empty($newBack[$newBackLink[$item['id']]]) ? $newBack[$newBackLink[$item['id']]] : [];
                    if ($newBackInfo) {
                        if ($newBackInfo['back_rate_type'] == 0) {
                            $data[$key]['echo_rate'] = $newBackInfo['echo_rate'];
                        } else {
                            $data[$key]['echo_rate'] = $newBackInfo['pass'] .':'. $newBackInfo['leak'];
                        }
                    }
                }
            }
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data,
            'in_investment_num' => count($data),
            'sync_time' => $syncTimeLiuYi,
            'sync_time_guang_zhou' => $syncTimeGuangZhou
        ];

        return $result;
    }

    // 腾讯今日实时在投数据
    public function getTencentInvestingData($params)
    {
        $where[] = ['media_id', '=', 4];
        $where[] = ['link_switch', '=', 1];
        $where[] = ['advertiser_id', '<>', ''];

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 账户id搜索
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }

        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }

        // 公司搜索
        if (!empty($params['company_id'])) {
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        }

        // 分销商链接不查询
        $distributorResponsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['is_distributor' => 1], 'id');
        $distributorResponsibilityPersonPids = array_column($distributorResponsibilityPerson, 'id');

        $distributorPitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $distributorResponsibilityPersonPids], 'id, pid');
        $distributorResponsibilityPersonIds = array_column($distributorPitcher, 'id');

        $where[] = ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds];
        $linkData = $this->model->getDataByWhere($where, 'id, video_id, advertiser_id, responsibility_person_id, version, rebate, echo_rate, subject_id');

        $date = date('Y-m-d');
        $data = $responsibilityPersonIds = [];

        $totalClickNum = $totalNewUserCount = 0;

        // 获取redis花费数据
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $developerInfo = config('tencent.developer_info');
        $token = Common::getTencentAdDeveloperAppAccessToken($developerInfo);
        $url = 'https://api.e.qq.com/v1.3/realtime_cost/get';
        $getBalanceUrl = 'https://api.e.qq.com/v1.3/funds/get';

        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            $commonParameters = [
                'access_token' => $token,
                'timestamp' => time(),
                'nonce' => md5(uniqid('', true))
            ];

            $parameters = [
                'account_id' => $value['advertiser_id'],
                'level' => 'ADVERTISER',
                'date' => $date,
                'page' => 1,
                'page_size' => 10
            ];

            $parameters = array_merge($commonParameters, $parameters);

            foreach ($parameters as $key => $item) {
                if (!is_string($item)) {
                    $parameters[$key] = json_encode($item);
                }
            }

            $requestUrl = $url . '?' . http_build_query($parameters);

            $response = Common::curlRequest($requestUrl);
            $costData = json_decode($response, true);
            // dump($costData);die;
            // 花费
            $value['cost'] = 0;
            if (!empty($costData['data']['list'][0])) {
                $value['cost'] = round($costData['data']['list'][0]['cost'] / 100, 2);
            }

            // 获取余额
            // dump($value['advertiser_id']);
            $commonParameters['nonce'] = md5(uniqid('', true));
            $balanceParams = [
                'account_id' => $value['advertiser_id']
            ];
            $balanceParams = array_merge($commonParameters, $balanceParams);

            foreach ($balanceParams as $k => $val) {
                if (!is_string($val)) {
                    $balanceParams[$k] = json_encode($val);
                }
            }

            $requestBalanceUrl = $getBalanceUrl . '?' . http_build_query($balanceParams);

            $response = Common::curlRequest($requestBalanceUrl);
            $balanceData = json_decode($response, true);

            $value['balance'] = 0;
            foreach ($balanceData['data']['list'] as $balanceVal) {
                $value['balance'] += $balanceVal['balance'];
            }
            $value['balance'] = round($value['balance'] / 100, 2);

            // dump($balanceData);die;

            $data[] = $value;
            $responsibilityPersonIds[] = $value['responsibility_person_id'];

            // 获取后台打开投放开关的投放账户
            // unset($redisCostData[$value['advertiser_id']]);
        }

        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id , type , uid, total_fee, activation_time, pay_merchant');

            $newUserPayData = $rechargeNumber = $newUserNum = $newActivityPayData = $tencentPayData = [];

            if ($userInfo) {
                $newUids = array_column($userInfo, 'id');
                $totalNewUserCount = count($newUids);
                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $userData = array_count_values($links);
            }

            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['type'] == config('enum.activity_pay_type', 13)) {
                        $newActivityPayData[$value['link_id']][] = $value['total_fee'];
                    }
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                $activityRecharge = empty($newActivityPayData[$item['id']]) ? 0 : array_sum($newActivityPayData[$item['id']]);
                $data[$key]['activity_recharge'] = round($activityRecharge, 2); // 活动充值

                // by huangxiaoshan 2023-07-12 当期充值95折扣
                $tencentTenPercent = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;

                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRechargeDiscount / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;

                // 转化率
                $data[$key]['conversion_rate'] = !empty($userData[$item['id']]) ? round($newUserNumber / $userData[$item['id']] * 100, 2) . '%' : '0%';
                $totalClickNum += empty($userData[$item['id']]) ? 0 : $userData[$item['id']];

                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge; // 当天累计充值暂时等于当期充值

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['media_id'] = 1; // 抖音

                // 实际花费
                $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);

                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($actualCost / $newUserNumber, 2); // 转化成本
                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($actualCost / $userData[$item['id']], 2) : 0; // 粉丝成本
                unset($data[$key]['rebate']);

                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRechargeDiscount / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-12 新增95折净利润
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况

                // by huangxiaoshan 2023-07-24 人均订单数.
                $data[$key]['avg_person_order'] = 0;
                if ($newRechargeNumber && $newUserNumber) {
                    $data[$key]['avg_person_order'] = round(bcdiv((string)$newRechargeNumber, (string)$newUserNumber, 3), 2);
                }
                // end
                unset($data[$key]['subject_id']);
            }
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data,
            'in_investment_num' => count($data)
        ];

        return $result;
    }

    // 获取快手今日实时在投数据
    public function getKuaiInvestingData($params)
    {
        $where[] = ['media_id', '=', 2];
        $totalClickNum = $totalNewUserCount = 0;

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        // 公司搜索
        if (!empty($params['company_id'])) {
            // $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $key1 = config('redis_key.kwai_real_time_investment_create_time') . date('Ymd');
        $key2 = config('redis_key.kwai_real_time_investment_link_user_register_num');

        // 取缓存数据
        if ($timeStamp = $redis->get($key1)) {

            $timeStamp = $redis->get($key1);
            $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();

            $totalClickNum = 0;
            foreach ($data as $key => $item) {
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                $clickNum = $redis->get($redisKey);
                $totalClickNum = $totalClickNum + $clickNum;

                // 获取当日累计注册用户数
                $linkRegisterUserNum = $redis->get($key2 . $item['id']);
                $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
            }
            return [
                'create_time' => date('Y-m-d H:i:s', $timeStamp),
                'total_click_num' => $totalClickNum,
                'total_new_user' => $totalNewUserCount,
                'data' => $data
            ];
        }

        $linkData = $this->model->getDataByWhere(['link_switch' => 1, 'media_id' => 2], 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, rebate, echo_rate,link_type');

        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $accessToken = Common::getKwaiAccessToken($appId, $secret);

        $hearder['headers'] = ['Access-Token: ' . $accessToken];
        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];
        $url = 'https://ad.e.kuaishou.com/rest/openapi/v1/advertiser/fund/daily_flows';

        // 
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            // 获取成本
            $requestData = [
                'advertiser_id' => intval($value['advertiser_id']),
                'start_date' => $startDate,
                'end_date' => $endDate,
            ];

            $result = Common::_curl($url, $requestData, 'POST', $hearder);
            $result = json_decode($result, true);

            if (!$result['code']) {
                $value['cost'] = empty($result['data']['details'][0]['daily_charge']) ? 0 : $result['data']['details'][0]['daily_charge']; // 今日花费
                $data[] = $value;
            } else {
                return ['message' => $result['message'] . '：link_id：' . $value['id']];
            }

            $accountIds[] = $value['advertiser_id'];
            $responsibilityPersonIds[] = $value['responsibility_person_id'];
        }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time, pay_merchant');

            $newUids = $newUserPayData = $rechargeNumber = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $userData = array_count_values($links);
            }

            $newUserNum = $tencentPayData = [];
            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                // $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点数据
            $launchAccountData = $this->launchAccountModel->getDataByWhere(['account_id' => $accountIds], 'account_id, rebate');
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-12 当期充值95折扣
                $virtualPayment = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2);
                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRecharge / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                // 转化率
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                $clickNum = $redis->get($redisKey);
                if (empty($clickNum) || empty($newUserNum[$item['id']])) {
                    $data[$key]['conversion_rate'] = '0%';
                } else {
                    $data[$key]['conversion_rate'] = round($newUserNumber / $clickNum * 100, 2) . '%';
                }

                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($item['cost'] / $userData[$item['id']]) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                $redis->set($key2 . $item['id'], $userLinkRegisterNum, 15 * 60);
                $data[$key]['media_id'] = 2; // 快手

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } else if (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                unset($data[$key]['rebate']);
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-12 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
            }
        }

        Db::name('real_time_data_cache')->where(['media_id' => 2])->delete(true);
        $bool = Db::name('real_time_data_cache')->insertAll($data);
        if ($bool) {
            $redis->set($key1, time(), 15 * 60); // 数据产生的时间
        }

        $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
        foreach ($data as $item) {

            // 获取点击数
            $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
            $clickNum = $redis->get($redisKey);
            $totalClickNum = $totalClickNum + $clickNum;

            // 获取当日累计注册用户数
            $linkRegisterUserNum = $redis->get($key2 . $item['id']);
            $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data
        ];

        return $result;
    }

    // 获取投放数据列表
    public function getLaunchDataList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];

        $totalCost = 0;
        $totalCurrentRecovery = 0;
        $totalCurrentRecharge = 0;
        $totalActualCost = 0;
        $totalCurrentRechargeDiscount = 0;
        $totalCurrentRechargeProfit = 0;
        $countRecharge = 0;
        $totalRechargeDiscount = 0;

        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }
        if (!empty($params['platform'])) {
            $where[] = ['platform', '=', $params['platform']];
        }
        if(!empty($params['date_time'])){
            $date_time = explode('~', $params['date_time']);
            $where[] = ['date','>=',date('Ymd', strtotime($date_time[0]))];
            $where[] = ['date','<=',date('Ymd', strtotime($date_time[1]))];
        }
        // 链接类型搜索
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
            $where[] = ['platform', '=', 1];

            $offset = ($page - 1) * $limit;
            $dateCountNumArray = Db::name('daily_delivery_data')->where($where)->field('date')->group('date')->order('date desc')->select()->toArray();
            $dateCountNumArray = array_column($dateCountNumArray, 'date');
            $total = count($dateCountNumArray);

            $totalPage = ceil($total / $limit);

            if ($total == 0) {
                return ['total' => 0, 'total_page' => 0, 'data' => []];
            }

            $date = array_slice($dateCountNumArray, $offset, $limit);
            $where[] = ['date', 'in', $date];

            $data = Db::name('daily_delivery_data')->where($where)->order('id desc')->select()->toArray();
            $launchDate = [];
            foreach ($data as $item) {
                $launchDate[$item['date']][] = $item;
            }

            $result = [];
            $totalVirtualPayment = 0;
            foreach ($date as $dateYmd) {

                if (!empty($launchDate[$dateYmd])) {
                    $cost = 0; // 花费
                    $actualCost = 0; // 实际花费
                    $registerUserNum = 0; // 注册人数
                    $activationUserNum = 0; // 激活人数
                    $currentRecharge = 0; // 当期充值
                    $newUserNumber = 0; // 新充人数
                    $rechargeUserNum = 0; // 充值人数
                    $totalRecharge = 0; // 累计充值
                    $virtualPayment = 0; // 腾讯虚拟支付金额
                    $totalIncome = 0; // 累计收益
                    $allCost = 0;
                    $nonGrantCost = 0; // 账户非赠款消耗(元)
                    $grantCost = 0; // 账户赠款消耗
                    $returnGoodsWalletCost = 0; // 共享赠款消耗
                    $balance = 0; // 账户总余额
                    $nonGrantBalance = 0; // 账户非赠款余额
                    $grantBalance = 0; // 账户赠款余额

                    foreach ($launchDate[$dateYmd] as $item) {
                        $cost += $item['cost'];
                        $actualCost += $item['actual_cost'];
                        $registerUserNum += $item['register_user_num'];
                        $activationUserNum += $item['activation_user_num'];
                        if ($dateYmd < '20230821') {
                            $currentRecharge += round($item['current_recharge'] * 0.95, 2);
                            $totalIncome += round($item['total_recharge'] * 0.95, 2);
                        } else {
                            $currentRecharge += round($item['current_recharge'] * 0.9 , 2);
                            $totalIncome += round($item['total_recharge'] * 0.9, 2);
                        }
                        $totalRecharge += $item['total_recharge'];
                        $newUserNumber += $item['new_user_number'];
                        $rechargeUserNum += $item['conversion_number'];
                        $virtualPayment += $item['virtual_payment'];
                        $allCost += $item['all_cost'];
                        $nonGrantCost += $item['non_grant_cost'];
                        $grantCost += $item['grant_cost'];
                        $returnGoodsWalletCost += $item['return_goods_wallet_cost'];
                        $balance += $item['balance'];
                        $nonGrantBalance += $item['non_grant_balance'];
                        $grantBalance += $item['grant_balance'];
                    }
                    $totalRechargeDiscount += $totalIncome;
                    $countRecharge += $totalRecharge;
                    $totalCost += $cost;
                    $totalActualCost += $actualCost;
                    $totalCurrentRecharge += $currentRecharge;
                    $totalVirtualPayment += $virtualPayment;
                    // 当期营收
                    $currentRechargeDiscount = round($currentRecharge, 2);
                    $totalCurrentRechargeDiscount += $currentRechargeDiscount;

                    // 当期利润
                    $currentRechargeProfit = round($totalIncome - $actualCost, 2);

                    $result[] = [
                        'platform' => 1,
                        'date' => substr($dateYmd, 0, 4).'-'.substr($dateYmd, 4, 2).'-'.substr($dateYmd, 6, 2),
                        'total_cost' => round($cost, 2),
                        'actual_cost' => round($actualCost, 2),
                        'register_user_num' => $registerUserNum,
                        'activation_user_num' => $activationUserNum,
                        'current_recharge' => round($currentRecharge, 2),
                        'current_recharge_discount' => $currentRechargeDiscount,
                        'current_recharge_profit' => $currentRechargeProfit,
                        'current_recovery' => $cost == 0 ? 0 : round($currentRechargeDiscount / $cost * 100, 2) . '%',
                        'actual_recovery' => $actualCost == 0 ? 0 : round($currentRechargeDiscount / $actualCost * 100, 2) . '%',
                        'conversion_rate' => empty($activationUserNum) ? '0%' : round($newUserNumber / $activationUserNum * 100, 2) . '%',
                        'recharge_user_num' => $rechargeUserNum,
                        'total_recharge' => round($totalRecharge, 2),
                        'total_income' => round($totalIncome, 2),
                        'total_recovery' => !empty(intval($actualCost)) ? round($totalIncome / $actualCost * 100, 2) . '%' : '0%',
                        'fans_cost' => !empty($activationUserNum) ? round($actualCost / $activationUserNum, 2) : 0,
                        'revenue' => round($totalIncome - $actualCost, 2),
                        'per_capita_contribution' => !empty($rechargeUserNum) ? round($totalRecharge / $rechargeUserNum, 2) : 0,
                        'all_cost' => round($allCost, 2),
                        'non_grant_cost' => round($nonGrantCost, 2),
                        'grant_cost' => round($grantCost, 2),
                        'return_goods_wallet_cost' => round($returnGoodsWalletCost, 2),
                        'balance' => round($balance, 2),
                        'non_grant_balance' => round($nonGrantBalance, 2),
                        'grant_balance' => round($grantBalance, 2)
                    ];
                }
            }

            $totalData = [
                'total_cost' => round($totalCost, 2),
                'total_actual_cost' => round($totalActualCost, 2),
                'total_current_recharge' => round($totalCurrentRecharge, 2),
                'total_current_recovery' => $totalCost == 0 ? '0%' : round($totalCurrentRechargeDiscount / $totalCost * 100, 2) . '%',
                'total_actual_recovery' => $totalActualCost == 0 ? '0%' : round($totalCurrentRechargeDiscount / $totalActualCost * 100, 2) . '%',
                'total_current_recharge_discount' => round($totalCurrentRecharge, 2),
                'total_current_recharge_profit' => round($totalRechargeDiscount - $totalActualCost, 2),
                'total_recharge' => round($countRecharge, 2),
                'total_recharge_discount' => round($totalRechargeDiscount, 2),
                'total_recovery' => $totalActualCost == 0 ? '0%' : round($totalRechargeDiscount / $totalActualCost * 100, 2) . '%',
            ];

            return ['total' => $total, 'total_page' => $totalPage, 'total_data' => $totalData, 'data' => $result];
        }

        $offset = ($page - 1) * $limit;
        $total = Db::name('delivery_data')->where($where)->count();
        $totalPage = ceil($total / $limit);

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }
        $data = Db::name('delivery_data')->where($where)->order('id desc')->limit($offset, $limit)->select()->toArray();
        $date = array_column($data, 'date');

        foreach ($data as $key => $value) {

            // by huangxiaoshan 2023-07-12 当期充值95折扣
            $virtualPayment = empty($value['virtual_payment']) ? 0 : $value['virtual_payment'];
            if ($value['date'] <= '20230821') {
                $currentRechargeDiscount = round($value['current_recharge'] * 0.95, 2);
                $totalIncome = round($value['total_recharge'] * 0.95, 2);
            } else {
                $currentRechargeDiscount = round($value['current_recharge'] * 0.9, 2);
                $totalIncome = round($value['total_recharge'] * 0.9, 2);
            }
            $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
            $data[$key]['current_recovery'] = $value['total_cost'] != 0 ? round($currentRechargeDiscount / $value['total_cost'] * 100, 2) . '%' : '0%';
            $data[$key]['actual_recovery'] = $value['actual_cost'] != 0 ? round($currentRechargeDiscount / $value['actual_cost'] * 100, 2) . '%' : '0%';

            // by huangxiaoshan 2023-07-12 当期充值95折扣后净利润.
            $data[$key]['current_recharge_profit'] = round($totalIncome - $value['actual_cost'], 2);
            $data[$key]['total_income'] = round($totalIncome, 2);
            $data[$key]['total_recovery'] = $value['actual_cost'] != 0 ? round($totalIncome / $value['actual_cost'] * 100, 2).'%' : '0%';
            $data[$key]['all_cost'] = empty($value['all_cost']) ? 0 : $value['all_cost'];
            $data[$key]['non_grant_cost'] = empty($value['non_grant_cost']) ? 0 : $value['non_grant_cost'];
            $data[$key]['grant_cost'] = empty($value['grant_cost']) ? 0 : $value['grant_cost'];
            $data[$key]['return_goods_wallet_cost'] = empty($value['return_goods_wallet_cost']) ? 0 : $value['return_goods_wallet_cost'];
            $data[$key]['balance'] = empty($value['balance']) ? 0 : $value['balance'];
            $data[$key]['non_grant_balance'] = empty($value['non_grant_balance']) ? 0 : $value['non_grant_balance'];
            $data[$key]['grant_balance'] = empty($value['grant_balance']) ? 0 : $value['grant_balance'];

            $data[$key]['date'] = substr($value['date'], 0, 4) . '-' . substr($value['date'], 4, 2) . '-' . substr($value['date'], 6, 2);
        }

        if (!empty($data)) {
            $deliveryData = Db::name('delivery_data')->where($where)->field(
                [
                    'sum(total_cost)total_cost',
                    'sum(current_recharge)total_current_recharge',
                    'sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end)total_current_recharge_discount',
                    'sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end)total_recharge_discount',
                    'sum(current_recovery)total_current_recovery',
                    'sum(actual_cost)total_actual_cost',
                    'sum(total_recharge) total_recharge',
                    'sum(virtual_payment)total_virtual_payment'
                ]
            )->select()->toArray();

            $totalCost = round(current($deliveryData)['total_cost'], 2);
            $totalActualCost = round(current($deliveryData)['total_actual_cost'], 2);
            $totalCurrentRecharge = round(current($deliveryData)['total_current_recharge'], 2);

            $totalVirtualPayment = round(current($deliveryData)['total_virtual_payment'], 2);
            $totalCurrentRecovery = $totalActualCost == 0 ? 0 : round($totalCurrentRecharge / $totalActualCost * 100, 2) . '%';
            $totalCurrentRechargeDiscount = round(current($deliveryData)['total_current_recharge_discount'], 2);
            $totalRechargeDiscount = round(current($deliveryData)['total_recharge_discount'], 2);
            $totalCurrentRechargeProfit = round($totalRechargeDiscount - $totalActualCost, 2);
        }

        $totalData = [
            'total_cost' => $totalCost,
            'total_actual_cost' => $totalActualCost,
            'total_current_recharge' => $totalCurrentRecharge,
            'total_current_recharge_discount' => $totalCurrentRechargeDiscount,
            'total_current_recharge_profit' => $totalCurrentRechargeProfit,
            'total_current_recovery' => $totalCost == 0 ? '0%' : round($totalCurrentRechargeDiscount / $totalCost * 100, 2) . '%',
            'total_actual_recovery' => $totalActualCost == 0 ? '0%' : round($totalCurrentRechargeDiscount / $totalActualCost * 100, 2) . '%',
            'total_recharge' => round(current($deliveryData)['total_recharge'], 2),
            'total_recharge_discount' => $totalRechargeDiscount,
            'total_recovery' => $totalActualCost == 0 ? '0%' : round($totalRechargeDiscount / $totalActualCost * 100, 2) . '%',
        ];

        return ['total' => $total, 'total_page' => $totalPage, 'total_data' => $totalData, 'data' => $data];
    }

    // 获取投放数据详情
    public function getLaunchDataDetail($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $date = str_replace('-', '', $params['date']);

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        if (!empty($params['media_id']) && $params['media_id'] == 1) {
            $redisKey = config('redis_key.huge_amount_advertising_account_info');
        } elseif (!empty($params['media_id']) && $params['media_id'] == 2) {
            $redisKey = config('kwai.magnetic_force_advertising_account_info');
        } else if (!empty($params['media_id']) && $params['media_id'] == 3) {
            $redisKey = config('baidu.baidu_sub_user_list');
            $advertiserData = $redis->hGetAll($redisKey);
        }
        $where[] = ['platform', '=', $params['media_id']];

        // 短剧id
        if (!empty($params['video_id'])) {
            $linkData = $this->model->getDataByWhere(['video_id' => $params['video_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 链接id
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        // 广告账号
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        // 负责人账号
        if (!empty($params['responsibility_person_id'])) {
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $params['responsibility_person_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 1=微信小程序 2=抖音小程序 3=h5 4=app
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }

        // 公司搜索
        if (!empty($params['company_id'])) {
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds, 'media_id' => $params['media_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 搜索指定日期
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        if (empty($params['start_date']) && empty($params['end_date'])) {
            $where[] = ['date', '=', $date];
        }

        $offset = ($page - 1) * $limit;
        $total = Db::name('daily_delivery_data')->where($where)->count();
        $totalPage = ceil($total / $limit);

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $fields = 'date, platform, link_id, advertiser_id, cost, current_recharge, current_recovery, conversion_number, conversion_cost, new_recharge_number, new_user_number, conversion_rate, fans_cost, total_recharge, revenue, per_capita_contribution, register_user_num, actual_cost, activation_user_num';

        if (!empty($params['cost_sort'])) {
            $order = 'cost ' . $params['cost_sort'];
        } else if (!empty($params['actual_cost_sort'])) {
            $order = 'actual_cost ' . $params['actual_cost_sort'];
        } else {
            $order = 'id desc';
        }

        $data = Db::name('daily_delivery_data')->field($fields)->where($where)->order($order)->limit($offset, $limit)->select()->toArray();

        $linkIds = array_column($data, 'link_id');
        $linkData = $this->model->getDataByWhere(['id' => $linkIds], 'id, video_id');
        $videoIds = array_column($linkData, 'video_id');
        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
        $video = [];
        foreach ($videoData as $key => $value) {
            foreach ($linkData as $k => $item) {
                if ($item['video_id'] == $value['id']) {
                    $video[$item['id']] = $value['name'];
                }
            }
        }

        $linkData = $this->model->getDataByWhere(['id' => $linkIds], 'id, responsibility_person_id');
        $responsibilityPersonIds = array_column($linkData, 'responsibility_person_id');
        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
        $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

        foreach ($linkData as $key => $value) {
            $linkData[$key]['responsibility_person_name'] = $responsibilityPerson[$value['responsibility_person_id']];
        }
        $linkAndResponsibilityPersonData = array_column($linkData, 'responsibility_person_name', 'id');

        // if ($params['media_id'] == 1 || $params['media_id'] == 2) {
        //     // 抖音和快手
        //     $length = $redis->scard($redisKey);
        //     $redisData = $advertiserData = [];

        //     if ($length) {
        //         $result = $redis->smembers($redisKey);
        //         foreach ($result as $item) {
        //             $redisData[] = json_decode($item, true);
        //         }
        //         $advertiserData = array_column($redisData, 'advertiser_name', 'advertiser_id'); // advertiser_id,advertiser_name
        //     }
        // }

        try {
            foreach ($data as $key => $value) {
                $data[$key]['date'] = substr($value['date'], 0, 4) . '-' . substr($value['date'], 4, 2) . '-' . substr($value['date'], 6, 2);
                $data[$key]['video_name'] = empty($video[$value['link_id']]) ? '' : $video[$value['link_id']];
                // $data[$key]['advertiser_name'] = empty($advertiserData[$value['advertiser_id']]) ? '' : $advertiserData[$value['advertiser_id']];

                if ($value['date'] >= 20230821) {
                    $data[$key]['total_income'] = round($value['total_recharge'] * 0.9, 2);
                    $data[$key]['current_income'] = round($value['current_recharge'] * 0.9, 2);
                } else {
                    $data[$key]['total_income'] = round($value['total_recharge'] * 0.95, 2);
                    $data[$key]['current_income'] = round($value['current_recharge'] * 0.95, 2);
                }
                $data[$key]['current_recovery'] = !empty(intval($value['actual_cost'])) ? round($data[$key]['current_income'] / $value['actual_cost'] * 100, 2) . '%' : '0%';
                $data[$key]['total_recovery'] = !empty(intval($value['actual_cost'])) ? round($data[$key]['total_income'] / $value['actual_cost'] * 100, 2) . '%' : '0%';
                $data[$key]['responsibility_person_name'] = $linkAndResponsibilityPersonData[$value['link_id']];
                $data[$key]['revenue'] = round($data[$key]['total_income'] - $value['actual_cost'], 2);
            }
        } catch (\Exception $e) {
            dump($value);
            die;
        }

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 获取投放总览查看统计数据
    public function getLaunchDataDetailCount($params)
    {
        $date = str_replace('-', '', $params['date']);
        $where[] = ['platform', '=', $params['media_id']];

        // 短剧id
        if (!empty($params['video_id'])) {
            $linkData = $this->model->getDataByWhere(['video_id' => $params['video_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 链接id
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        // 广告账号
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        // 负责人账号
        if (!empty($params['responsibility_person_id'])) {
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $params['responsibility_person_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 公司搜索
        if (!empty($params['company_id'])) {
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds, 'media_id' => $params['media_id']], 'id');
            $where[] = ['link_id', 'in', array_column($linkData, 'id')];
        }

        // 1=微信小程序 2=抖音小程序 3=h5 4=app
        if (!empty($params['link_type'])) {
            $where[] = ['link_type', '=', $params['link_type']];
        }

        // 搜索指定日期
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', date('Ymd', strtotime($params['start_date']))];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', date('Ymd', strtotime($params['end_date']))];
        }

        if (empty($params['start_date']) && empty($params['end_date'])) {
            $where[] = ['date', '=', $date];
        }
        $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(conversion_number) as conversion_number, sum(new_recharge_number) as new_recharge_number, sum(new_user_number) as new_user_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_income, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->where($where)->find();

        $data['revenue'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = !empty($data['actual_cost']) ? round($data['current_income'] / $data['actual_cost'] * 100, 2) . '%' : '0%';
        $data['total_recovery'] = !empty($data['actual_cost']) ? round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%' : '0%';

        $data['total_income'] = round($data['total_income'], 2);
        $data['current_income'] = round($data['current_income'], 2);
        return $data;
    }

    /**
     * 获取巨量纵横组织账户下的所有广告账户信息
     *
     * @param array params
     * @return array
     * @author zhixiang0215@126.com
     */
    public function getAccountSelectList($params)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        if (!empty($params['subject_id']) && $params['subject_id'] == 8) {
            $redisKey = config('redis_key.huge_amount_yishu_advertising_account_info');
        } else if (!empty($params['subject_id']) && $params['subject_id'] == 24) {
            $redisKey = config('redis_key.huge_amount_xingcan_advertising_account_info');
        }
        // else if (!empty($params['subject_id']) && in_array($params['subject_id'], config('tiktok.penshang'))) {
        //     $redisKey = config('redis_key.huge_amount_sixseals_erfen_advertising_account_info');
        // } 
        else {
            $redisKey = config('redis_key.huge_amount_advertising_account_info');
        }
        $length = $redis->scard($redisKey);
        $data = [];

        if ($length && empty($params['is_refresh'])) {
            $result = $redis->smembers($redisKey);

            foreach ($result as $item) {
                $data[] = json_decode($item, true);
            }

            // 光标事件搜索
            if (!empty($params['advertiser_name'])) {
                $searchData = [];
                foreach ($data as $key => $value) {
                    if (strstr($value['advertiser_name'], $params['advertiser_name'])) {
                        $searchData[] = $value;
                    }
                }
                return $searchData;
            }

            return $data;
        }

        if (!empty($params['subject_id']) && $params['subject_id'] == 8) {
            $appId = config('tiktok.huge_amount_yaodao.app_id');
            $secret = config('tiktok.huge_amount_yaodao.secret');
        } else if (!empty($params['subject_id']) && $params['subject_id'] == 24) {
            $appId = config('tiktok.huge_amount_xingcan.app_id');
            $secret = config('tiktok.huge_amount_xingcan.secret');
        }
        // else if (!empty($params['subject_id']) && in_array($params['subject_id'], config('tiktok.penshang'))) {
        //     $appId = config('tiktok.huge_amount_sixseals_erfen.app_id');
        //     $secret = config('tiktok.huge_amount_sixseals_erfen.secret');
        // } 
        else {
            $appId = config('tiktok.huge_amount.app_id');
            $secret = config('tiktok.huge_amount.secret');
        }

        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);

        $url = 'https://ad.oceanengine.com/open_api/oauth2/advertiser/get/';

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'access_token' => $accessToken
        ];

        $result = Common::_curl($url, $requestData, 'GET', ['json' => 1]);

        $result = json_decode($result, true);

        if ($result['code']) {
            return ['message' => $result['message']];
        }
        $redis->del($redisKey);

        $url = 'https://ad.oceanengine.com/open_api/2/majordomo/advertiser/select/';
        $hearder['headers'] = ['Access-Token:' . $accessToken];

        foreach ($result['data']['list'] as $key => $value) {

            if (empty($value['advertiser_id'])) {
                continue;
            }
            $advertiserId = $value['advertiser_id'];
            $requestData = ['advertiser_id' => $advertiserId];

            $result = Common::_curl($url, $requestData, 'GET', $hearder);
            $result = json_decode($result, true);
            if (!$result['code']) {
                foreach ($result['data']['list'] as $key => $value) {
                    $data[] = $value;
                    $redis->sadd($redisKey, json_encode($value));
                }
            }
        }

        $redis->expire($redisKey, 43200);

        return $data;
    }

    /**
     * 快手账户下拉列表
     *
     * @dateTime 2022/12/08
     * @return string|array
     * @author zhixiang0215@126.com
     */
    public function getKwaiAccountSelectList($params)
    {
        $kwaiId = config('kwai.kwai_id');

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $redisKey = config('kwai.magnetic_force_advertising_account_info');
        $length = $redis->scard($redisKey);
        $data = [];

        if ($length && empty($params['is_refresh'])) {
            $result = $redis->smembers($redisKey);

            foreach ($result as $item) {
                $data[] = json_decode($item, true);
            }

            // 光标事件搜索
            if (!empty($params['advertiser_name'])) {
                $searchData = [];
                foreach ($data as $key => $value) {
                    if (strstr($value['advertiser_name'], $params['advertiser_name'])) {
                        $searchData[] = $value;
                    }
                }
                return $searchData;
            }
            return $data;
        }

        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $accessToken = Common::getKwaiAccessToken($appId, $secret);

        $url = 'https://ad.e.kuaishou.com/rest/openapi/gw/uc/v1/advertisers';

        $header['headers'] = ['Access-Token:' . $accessToken, 'Content-Type: application/json'];
        $header['json'] = 1;
        $requestData = ['advertiser_id' => $kwaiId];
        $result = Common::_curl($url, $requestData, 'POST', $header);

        $result = json_decode($result, true);

        if ($result['code']) {
            return ['message' => $result['message']];
        }
        $redis->del($redisKey);

        foreach ($result['data']['details'] as $key => $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            if (!empty($value['corporation_name'])) {
                unset($value['corporation_name']);
            }
            $data[] = $value;
            $redis->sadd($redisKey, json_encode($value));
        }

        $redis->expire($redisKey, 43200);

        return $data;
    }

    // 按短剧统计
    public function getByShortPlayList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where =$linkwhere=$datawhere= [];
        if (!empty($params['video_id'])) {
            $where[] = ['id', '=', $params['video_id']];
        }

        if (!empty($params['original_id'])) {
            $where[] = ['original_id', '=', $params['original_id']];
        }

        if (!empty($params['start_date'])) {
            $where[] = ['created_at', '>=', strtotime($params['start_date'])];
        }
        //公司id
        if(!empty($params['company_id'])){
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id, name');
            $responsibilityPersonId = array_column($responsibilityPerson, 'id');
            $linkwhere['responsibility_person_id']=$responsibilityPersonId;
        }
        //负责人id
        if(!empty($params['respons_id'])){
            if(!empty($responsibilityPersonId)){
                $respons_id=$responsibilityPersonId;
                $respons_id[]=$params['respons_id'];
            }else{
                $respons_id=$params['respons_id'];
            }
            $linkwhere['responsibility_person_id']=$respons_id;
        }
        //开始时间，结束时间
        if(!empty($params['start_time'])&&!empty($params['end_time'])){
            $datawhere[]=['date','>=',date('Ymd',strtotime($params['start_time'].' 00:00:00'))];
            $datawhere[]=['date','<=',date('Ymd',strtotime($params['end_time'].' 00:00:00'))];
        }

        $data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name, original_id');

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');
            $linkwhere['video_id']= $videoIds;
            $linkData = $this->model->getDataByWhere($linkwhere, 'id, video_id, responsibility_person_id');
            $link = [];
            foreach ($linkData as $key => $value) {
                $link[$value['video_id']][] = $value['id'];
            }

            $linkIds = array_column($linkData, 'id');
            $datawhere['link_id']=$linkIds;
            $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere($datawhere, 'link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, virtual_payment, date');

            $dailyDeliveryDataResult = [];
            foreach ($dailyDeliveryData as $key => $value) {
                foreach ($link as $videoId => $item) {
                    if (in_array($value['link_id'], $item)) {
                        $dailyDeliveryDataResult[$videoId][] = $value;
                    }
                }
            }

            foreach ($data['data'] as $key => $value) {

                $cost = $actualCost = $registerUserNum = $activationUserNum = $currentRecharge = $totalRecharge = $rechargeNumber = $conversionNumber = $perCapitaContribution = $revenue = $currentRechargeDiscount = 0;
                $virtualPayment = $totalIncome = 0;
                $currentRecovery = $totalRecovery = '0%';

                if (!empty($dailyDeliveryDataResult[$value['id']])) {

                    foreach ($dailyDeliveryDataResult[$value['id']] as $k => $item) {
                        $cost = $cost + $item['cost'];
                        $actualCost = $actualCost + $item['actual_cost'];
                        $registerUserNum = $registerUserNum + $item['register_user_num'];
                        $activationUserNum = $activationUserNum + $item['activation_user_num'];
                        $currentRecharge = $currentRecharge + $item['current_recharge'];
                        if ($item['date'] >= 20230821) {
                            $currentRechargeDiscount = $currentRechargeDiscount + $item['current_recharge'] * 0.9;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.9;
                        } else {
                            $currentRechargeDiscount = $currentRechargeDiscount + $item['current_recharge'] * 0.95;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.95;
                        }
                        $totalRecharge = $totalRecharge + $item['total_recharge'];
                        $rechargeNumber = $rechargeNumber + $item['recharge_number']; // 订单数
                        $conversionNumber = $conversionNumber + $item['conversion_number'];
                        $virtualPayment = $virtualPayment + $item['virtual_payment'];
                    }

                    $currentRecovery = intval($cost) == 0 ? '0%' : round($currentRechargeDiscount / $actualCost * 100, 2) . '%';
                    $totalRecovery = intval($cost) == 0 ? '0%' : round($totalIncome / $actualCost * 100, 2) . '%';
                }

                $data['data'][$key]['cost'] = round($cost, 2); // 花费
                $data['data'][$key]['actual_cost'] = round($actualCost, 2); // 实际花费
                $data['data'][$key]['register_user_num'] = $registerUserNum; // 注册人数
                $data['data'][$key]['activation_user_num'] = $activationUserNum; // 激活人数
                $data['data'][$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                $data['data'][$key]['current_recharge_discount'] = round($currentRechargeDiscount, 2);
                $data['data'][$key]['current_recharge_profit'] = round($totalIncome - $actualCost, 2);
                // end

                $data['data'][$key]['current_recovery'] = $currentRecovery; // 当期回收
                $data['data'][$key]['total_recharge'] = round($totalRecharge, 2); // 累计充值
                $data['data'][$key]['total_income'] = round($totalIncome, 2);
                $data['data'][$key]['total_recovery'] = $totalRecovery; // 累计回收
                $data['data'][$key]['recharge_number'] = $rechargeNumber; // 订单数
                $data['data'][$key]['conversion_number'] = $conversionNumber; // 充值人数
                $data['data'][$key]['conversion_cost'] = $conversionNumber ? round($actualCost / $conversionNumber, 2) : 0; // 转化成本

                $data['data'][$key]['revenue'] = round($totalIncome - $actualCost, 2); // 营收情况
                $data['data'][$key]['per_capita_contribution'] = $conversionNumber == 0 ? 0 : round($totalRecharge / $conversionNumber, 2); // 充值用户贡献
            }
        }
        return $data;
    }

    // 按短剧统计合计
    public function getByShortPlayCount($params)
    {
        $where =$linkwhere=$datawhere= [];
        if (!empty($params['video_id'])) {
            $where['id'] = $params['video_id'];
        }

        if (!empty($params['start_date'])) {
            $where[] = ['created_at', '>=', strtotime($params['start_date'])];
        }

        if (!empty($params['original_id'])) {
            $where['original_id'] = $params['original_id'];
        }
        if(!empty($params['company_id'])){
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id, name');
            $responsibilityPersonId = array_column($responsibilityPerson, 'id');
            $linkwhere['responsibility_person_id']=$responsibilityPersonId;
        }
        if(!empty($params['respons_id'])){
            if(!empty($responsibilityPersonId)){
                $respons_id=$responsibilityPersonId;
                $respons_id[]=$params['respons_id'];
            }else{
                $respons_id=$params['respons_id'];
            }
            $linkwhere['responsibility_person_id']=$respons_id;
        }
        if(!empty($params['start_time'])&&!empty($params['end_time'])){
            $datawhere[]=['date','>=',date('Ymd',strtotime($params['start_time'].' 00:00:00'))];
            $datawhere[]=['date','<=',date('Ymd',strtotime($params['end_time'].' 00:00:00'))];
        }
        try {
            if (empty($where)&&empty($linkwhere)) {
                $data = Db::name('daily_delivery_data')->where($datawhere)->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(conversion_number) as conversion_number, sum(new_recharge_number) as new_recharge_number, sum(recharge_number) as recharge_number, sum(new_user_number) as new_user_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_recharge_discount, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->select()->toArray();
                $data = $data[0];
            } else {
                if(!empty($where)) {
                    $videoData = $this->videosModel->getInfoByWhere($where, 'id');
                    if ($videoData) {
                        $linkwhere['video_id'] = $videoData['id'];
                    } else {
                        return [];
                    }
                }
                $linkData = $this->model->getDataByWhere($linkwhere, 'id');
                $linkIds = array_column($linkData, 'id');
                $dataWhere = [
                    ['link_id', 'in', $linkIds]
                ];
                if (!empty($params['start_date'])) {
                    $dataWhere[] = ['date', '>=', str_replace('-', '', $params['start_date'])];
                }
                if (!empty($params['end_date'])) {
                    $dataWhere[] = ['date', '<=', str_replace('-', '', $params['end_date'])];
                }

            $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(conversion_number) as conversion_number, sum(new_recharge_number) as new_recharge_number, sum(recharge_number) as recharge_number, sum(new_user_number) as new_user_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_recharge_discount, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->where(['link_id' => $linkIds])->where($datawhere)->find();
        }

        $data['current_recharge_profit'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = empty($data['actual_cost']) ? '0%' : round($data['current_recharge_discount'] / $data['actual_cost'] * 100, 2) . '%';
        $data['total_recovery'] = empty($data['actual_cost']) ? '0%' : round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%';
        $data['conversion_cost'] = empty($data['new_user_number']) ? 0 : round($data['actual_cost'] / $data['new_user_number'], 2);
        $data['per_capita_contribution'] = empty($data['conversion_number']) ? 0 : round($data['total_recharge'] / $data['conversion_number'], 2);

        $data['current_recharge_discount'] = round($data['current_recharge_discount'], 2);
        $data['total_recharge'] = round($data['total_recharge'], 2);
        $data['total_income'] = round($data['total_income'], 2);

            return $data;
        } catch (\Exception $e) {
            return [];
        }
    }

    // 每部短剧统计详细
    public function getShortPlayDetail($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $videoId = $params['video_id'];
        $linkwhere=$datawhere= [];
        if(!empty($params['company_id'])){
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id, name');
            $responsibilityPersonId = array_column($responsibilityPerson, 'id');
            $linkwhere['responsibility_person_id']=$responsibilityPersonId;
        }
        if(!empty($params['respons_id'])){
            if(!empty($responsibilityPersonId)){
                $respons_id=$responsibilityPersonId;
                $respons_id[]=$params['respons_id'];
            }else{
                $respons_id=$params['respons_id'];
            }
            $linkwhere['responsibility_person_id']=$respons_id;
        }
        if(!empty($params['start_time'])&&!empty($params['end_time'])){
            $datawhere[]=['date','>=',date('Ymd',strtotime($params['start_time'].' 00:00:00'))];
            $datawhere[]=['date','<=',date('Ymd',strtotime($params['end_time'].' 00:00:00'))];
        }
        $linkwhere['video_id']=$videoId;
        $linkData = $this->model->getDataByWhere($linkwhere, 'id, video_id, responsibility_person_id');
        $linkIds = array_column($linkData, 'id');
        $responsibilityPersonId = array_column($linkData, 'responsibility_person_id');
        $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonId], 'id, name');
        $responsibilityPersonData = array_column($responsibilityPerson, 'name', 'id');

        foreach ($linkData as $key => $value) {
            $linkData[$key]['responsibility_person_name'] = $responsibilityPersonData[$value['responsibility_person_id']];
        }
        $linkAndResponsibilityPerson = array_column($linkData, 'responsibility_person_name', 'id');
        $datawhere['link_id']=$linkIds;
        $data = $this->dailyDeliveryDataModel->getPagingDataByWhere($datawhere, $page, $limit, 'date, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, new_recharge_number, new_user_number, conversion_cost, conversion_rate, current_recovery');

        if ($data['data']) {

            foreach ($data['data'] as $key => $value) {

                if ($value['date'] >= 20230821) {
                    $data['data'][$key]['current_income'] = round($value['current_recharge'] * 0.9, 2);
                    $data['data'][$key]['total_income'] = round($value['total_recharge'] * 0.9, 2);
                } else {
                    $data['data'][$key]['current_income'] = round($value['current_recharge'] * 0.95, 2);
                    $data['data'][$key]['total_income'] = round($value['total_recharge'] * 0.95, 2);
                }
                $data['data'][$key]['date'] = substr($value['date'], 0, 4) . '-' . substr($value['date'], 4, 2) . '-' . substr($value['date'], 6, 2);
                $data['data'][$key]['revenue'] = round($data['data'][$key]['total_income'] - $value['actual_cost'], 2); // 营收情况
                $data['data'][$key]['per_capita_contribution'] = $value['conversion_number'] == 0 ? 0 : round($value['total_recharge'] / $value['conversion_number'], 2); // 充值用户贡献
                $data['data'][$key]['responsibility_person_name'] = $linkAndResponsibilityPerson[$value['link_id']];

                $data['data'][$key]['current_recovery'] = !empty(intval($value['actual_cost'])) ? round($data['data'][$key]['current_income'] / $value['actual_cost'] * 100, 2) . '%' : '0%';
                $data['data'][$key]['total_recovery'] = !empty(intval($value['actual_cost'])) ? round($data['data'][$key]['total_income'] / $value['actual_cost'] * 100, 2) . '%' : '0%';
            }
        }

        return $data;
    }

    // 按负责人统计列表
    public function getByPeopleList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $branchOfficeManage = $this->responsibilityPersonModel->getDataByWhere(['is_branch_office_manage' => 1], 'id');
        $manageIds = array_column($branchOfficeManage, 'id');

        $where = [
            ['is_distributor', '=', 0],
            ['pid', '=', null],
            ['is_branch_office_manage', '=', 0],
            ['id', 'not in', config('link.not_query')]
        ];

        $orWhere = ['pid' => $manageIds];
        // 投手搜索
        if (!empty($params['responsibility_person_id'])) {
            $where['id'] = $params['responsibility_person_id'];
            $orWhere['id'] = $params['responsibility_person_id'];
        }
        // 公司搜索
        if (!empty($params['company_id'])) {
            $where['company_id'] = $params['company_id'];
            $orWhere['company_id'] = $params['company_id'];
        }

        $data1 = $this->responsibilityPersonModel->getDataByWhere($orWhere, 'id, name');
        $data2 = Db::name('responsibility_person')->where($where)->field('id, name')->order('id desc')->select()->toArray();

        $data = array_merge($data1, $data2);

        if ($data) {
            $responsibilityPersonIds = array_column($data, 'id');
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id, responsibility_person_id');

            $link = [];
            foreach ($linkData as $key => $value) {
                $link[$value['responsibility_person_id']][] = $value['id'];
            }
            $linkIds = array_column($linkData, 'id');
            $where = [];
            $where[] = ['link_id', 'in', $linkIds];
            if (!empty($params['start_date'])) {
                $startDate = str_replace('-', '', $params['start_date']);
                $where[] = ['date', '>=', $startDate];
            }
            if (!empty($params['end_date'])) {
                $endDate = str_replace('-', '', $params['end_date']);
                $where[] = ['date', '<=', $endDate];
            }

            $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, virtual_payment');

            $dailyDeliveryDataResult = [];
            foreach ($dailyDeliveryData as $key => $value) {
                foreach ($link as $k => $item) {
                    if (in_array($value['link_id'], $item)) {
                        $dailyDeliveryDataResult[$k][] = $value;
                    }
                }
            }

            foreach ($data as $key => $value) {

                $cost = $actualCost = $registerUserNum = $activationUserNum = $currentRecharge = $totalRecharge = $rechargeNumber = $conversionNumber = $perCapitaContribution = $revenue = 0;
                $currentRecovery = $totalRecovery = '0%';
                $virtualPayment = $currentRechargeDiscount = $totalIncome = 0;

                if (!empty($dailyDeliveryDataResult[$value['id']])) {

                    foreach ($dailyDeliveryDataResult[$value['id']] as $k => $item) {
                        $cost = $cost + $item['cost'];
                        $actualCost = $actualCost + $item['actual_cost'];
                        $registerUserNum = $registerUserNum + $item['register_user_num'];
                        $activationUserNum = $activationUserNum + $item['activation_user_num'];
                        if ($item['date'] < 20230821) {
                            $currentRechargeDiscount = $currentRechargeDiscount + $item['current_recharge'] * 0.95;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.95;
                        } else {
                            $currentRechargeDiscount = $currentRechargeDiscount + $item['current_recharge'] * 0.9;
                            $totalIncome = $totalIncome + $item['total_recharge'] * 0.9;
                        }
                        $totalRecharge = $totalRecharge + $item['total_recharge'];
                        $currentRecharge = $currentRecharge + $item['current_recharge'];
                        $rechargeNumber = $rechargeNumber + $item['recharge_number']; // 订单数
                        $conversionNumber = $conversionNumber + $item['conversion_number'];
                        $virtualPayment = $virtualPayment + $item['virtual_payment'];
                    }

                    $currentRecovery = intval($actualCost) == 0 ? '0%' : round($currentRechargeDiscount / $actualCost * 100, 2) . '%';
                    $totalRecovery = intval($actualCost) == 0 ? '0%' : round($totalIncome / $actualCost * 100, 2) . '%';
                }

                $data[$key]['cost'] = round($cost, 2); // 花费
                $data[$key]['actual_cost'] = round($actualCost, 2); // 实际花费
                $data[$key]['register_user_num'] = $registerUserNum; // 注册人数
                $data[$key]['activation_user_num'] = $activationUserNum; // 激活人数
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                // by update huangxiaoshan 2023-07-13
                $data[$key]['current_recharge_discount'] = round($currentRechargeDiscount, 2);
                $data[$key]['current_recharge_profit'] = round($totalIncome - $actualCost, 2);
                // end
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                $data[$key]['current_recovery'] = $currentRecovery; // 当期回收
                $data[$key]['total_recharge'] = round($totalRecharge, 2); // 累计充值
                $data[$key]['total_income'] = round($totalIncome, 2);
                $data[$key]['total_recovery'] = $totalRecovery; // 累计回收
                $data[$key]['recharge_number'] = $rechargeNumber; // 订单数
                $data[$key]['conversion_number'] = $conversionNumber; // 充值人数

                $data[$key]['revenue'] = round($totalIncome - $actualCost, 2); // 营收情况
                $data[$key]['per_capita_contribution'] = $conversionNumber == 0 ? 0 : round($totalRecharge / $conversionNumber, 2); // 充值用户贡献
            }
        } else {
            $data = [];
        }
        return $data;
    }

    // 获取每个负责人统计详细
    public function getPeopleDetail($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $responsibilityPersonId = $params['id'];
        $where = ['responsibility_person_id' => $responsibilityPersonId];

        if (!empty($params['media_id'])) {
            $where['media_id'] = $params['media_id'];
        }

        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'name');
        $linkData = $this->model->getDataByWhere($where, 'id, responsibility_person_id');

        $linkIds = array_column($linkData, 'id');

        $total = Db::name('daily_delivery_data')->where(['link_id' => $linkIds])->group('month')->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }
        $totalPage = ceil($total / $limit);
        $offset = ($page - 1) * $limit;

        $data = Db::name('daily_delivery_data')->field('month')->where(['link_id' => $linkIds])->group('month')->order('month desc')->limit($offset, $limit)->select()->toArray();

        $month = array_column($data, 'month');
        $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere(['link_id' => $linkIds, 'month' => $month], 'month, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, new_recharge_number, new_user_number, conversion_cost, conversion_rate, current_recovery, date');

        $dailyDeliveryDataResult = [];
        foreach ($dailyDeliveryData as $key => $value) {
            $dailyDeliveryDataResult[$value['month']][] = $value;
        }

        foreach ($data as $key => $value) {
            $data[$key]['month'] = substr($value['month'], 0, 4) . '-' . substr($value['month'], 4, 2);
            $cost = $actualCost = $registerUserNum = $activationUserNum = $currentRecharge = $totalRecharge = $rechargeNumber = $conversionNumber = $perCapitaContribution = $revenue = $currentIncome = $totalIncome = 0;
            $currentRecovery = $totalRecovery = '0%';

            if (!empty($dailyDeliveryDataResult[$value['month']])) {

                foreach ($dailyDeliveryDataResult[$value['month']] as $item) {
                    $cost = $cost + $item['cost'];
                    $actualCost = $actualCost + $item['actual_cost'];
                    $registerUserNum = $registerUserNum + $item['register_user_num'];
                    $activationUserNum = $activationUserNum + $item['activation_user_num'];
                    $currentRecharge = $currentRecharge + $item['current_recharge'];
                    $totalRecharge = $totalRecharge + $item['total_recharge'];
                    $rechargeNumber = $rechargeNumber + $item['recharge_number']; // 订单数
                    $conversionNumber = $conversionNumber + $item['conversion_number'];

                    if ($item['date'] >= 20230821) {
                        $currentIncome = $currentIncome + $item['current_recharge'] * 0.9;
                        $totalIncome = $totalIncome + $item['total_recharge'] * 0.9;
                    } else {
                        $currentIncome = $currentIncome + $item['current_recharge'] * 0.95;
                        $totalIncome = $totalIncome + $item['total_recharge'] * 0.95;
                    }
                }

                $currentRecovery = intval($actualCost) == 0 ? '0%' : round($currentIncome / $actualCost * 100, 2) . '%';
                $totalRecovery = intval($actualCost) == 0 ? '0%' : round($totalIncome / $actualCost * 100, 2) . '%';
            }

            $data[$key]['cost'] = round($cost, 2); // 花费
            $data[$key]['actual_cost'] = round($actualCost, 2); // 实际花费
            $data[$key]['register_user_num'] = $registerUserNum; // 注册人数
            $data[$key]['activation_user_num'] = $activationUserNum; // 激活人数
            $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
            $data[$key]['current_income'] = round($currentIncome, 2);
            $data[$key]['current_recovery'] = $currentRecovery; // 当期回收
            $data[$key]['total_recharge'] = round($totalRecharge, 2); // 累计充值
            $data[$key]['total_income'] = round($totalIncome, 2);
            $data[$key]['total_recovery'] = $totalRecovery; // 累计回收
            $data[$key]['recharge_number'] = $rechargeNumber; // 订单数
            $data[$key]['conversion_number'] = $conversionNumber; // 充值人数
            $data[$key]['responsibility_person_name'] = $responsibilityPerson['name']; // 负责人
            $data[$key]['responsibility_person_id'] = $responsibilityPersonId;
            $data[$key]['revenue'] = round($totalIncome - $actualCost, 2); // 营收情况
            $data[$key]['per_capita_contribution'] = $conversionNumber == 0 ? 0 : round($totalRecharge / $conversionNumber, 2); // 充值用户贡献
        }
        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 每个负责人按月份合计
    public function getPeopleDetailCount($params)
    {
        $responsibilityPersonId = $params['id'];
        $where = ['responsibility_person_id' => $responsibilityPersonId];

        if (!empty($params['media_id'])) {
            $where['media_id'] = $params['media_id'];
        }

        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'name');
        $linkData = $this->model->getDataByWhere($where, 'id, responsibility_person_id');

        $linkIds = array_column($linkData, 'id');

        $data = Db::name('daily_delivery_data')->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(recharge_number) as recharge_number, sum(conversion_number) as conversion_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_income, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')->where(['link_id' => $linkIds])->find();

        $data['revenue'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = round($data['current_income'] / $data['actual_cost'] * 100, 2) . '%';
        $data['total_recovery'] = round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%';

        $data['total_income'] = round($data['total_income'], 2);
        $data['current_income'] = round($data['current_income'], 2);

        return $data;
    }

    // 获取指定负责人指定月份数据
    public function getPeopleListByMonth($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($params['responsibility_person_id']);

        $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $params['responsibility_person_id']], 'id');
        $linkIds = array_column($linkData, 'id');
        $where = [];
        // 链接ID搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        } else {
            $where[] = ['link_id', 'in', $linkIds];
        }
        // 日期搜索
        if (!empty($params['start_date'])) {
            $startDate = str_replace('-', '', $params['start_date']);
            $where[] = ['date', '>=', $startDate];
        }
        if (!empty($params['end_date'])) {
            $endDate = str_replace('-', '', $params['end_date']);
            $where[] = ['date', '<=', $endDate];
        }

        if (!empty($params['month'])) {
            $where[] = ['month', '=', str_replace('-', '', $params['month'])];
        }

        if (!empty($params['media_id'])) {
            $where[] = ['platform', '=', $params['media_id']];
        }

        $data = $this->dailyDeliveryDataModel->getPagingDataByWhere($where, $page, $limit, 'date, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, current_recovery, revenue, per_capita_contribution');

        foreach ($data['data'] as $key => $value) {
            $data['data'][$key]['date'] = substr($value['date'], 0, 4) . '-' . substr($value['date'], 4, 2) . '-' . substr($value['date'], 6, 2);
            
            $data['data'][$key]['responsibility_person_name'] = $responsibilityPerson['name'];
            if (empty($value['register_user_num'])) {
                $data['data'][$key]['register_user_num'] = 0;
            }
            if (empty($value['actual_cost'])) {
                $data['data'][$key]['actual_cost'] = 0;
            }

            if ($value['date'] >= 20230821) {
                $data['data'][$key]['current_income'] = round($value['current_recharge'] * 0.9, 2);
                $data['data'][$key]['total_income'] = round($value['total_recharge'] * 0.9, 2);
            } else {
                $data['data'][$key]['current_income'] = round($value['current_recharge'] * 0.95, 2);
                $data['data'][$key]['total_income'] = round($value['total_recharge'] * 0.95, 2);
            }
            $data['data'][$key]['current_recovery'] = intval($value['actual_cost']) == 0 ? '0%' : round($data['data'][$key]['current_income'] / $value['actual_cost'] * 100, 2) . '%';
            $data['data'][$key]['total_recovery'] = intval($value['actual_cost']) == 0 ? '0%' : round($data['data'][$key]['total_income'] / $value['actual_cost'] * 100, 2) . '%';
        }

        return $data;
    }

    // 获取指定负责人指定月份数据合计
    public function getPeopleListByMonthCount($params)
    {
        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($params['responsibility_person_id']);

        $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $params['responsibility_person_id']], 'id');
        $linkIds = array_column($linkData, 'id');
        $where = [];
        // 链接ID搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        } else {
            $where[] = ['link_id', 'in', $linkIds];
        }
        // 日期搜索
        if (!empty($params['start_date'])) {
            $startDate = str_replace('-', '', $params['start_date']);
            $where[] = ['date', '>=', $startDate];
        }
        if (!empty($params['end_date'])) {
            $endDate = str_replace('-', '', $params['end_date']);
            $where[] = ['date', '<=', $endDate];
        }

        if (!empty($params['month'])) {
            $where[] = ['month', '=', str_replace('-', '', $params['month'])];
        }

        if (!empty($params['media_id'])) {
            $where[] = ['platform', '=', $params['media_id']];
        }

        $data = Db::name('daily_delivery_data')->where($where)
            ->field('sum(cost) as cost, sum(actual_cost) as actual_cost, sum(register_user_num) as register_user_num, sum(activation_user_num) as activation_user_num, sum(current_recharge) as current_recharge, sum(total_recharge) as total_recharge, sum(recharge_number) as recharge_number, sum(conversion_number) as conversion_number, sum(revenue) as revenue, sum(case when date < 20230821 then current_recharge * 0.95 else current_recharge * 0.9 end) as current_income, sum(case when date < 20230821 then total_recharge * 0.95 else total_recharge * 0.9 end) as total_income')
            ->find();

        $data['revenue'] = round($data['total_income'] - $data['actual_cost'], 2);
        $data['current_recovery'] = round($data['current_income'] / $data['actual_cost'] * 100, 2) . '%';
        $data['total_recovery'] = round($data['total_income'] / $data['actual_cost'] * 100, 2) . '%';

        $data['total_income'] = round($data['total_income'], 2);
        $data['current_income'] = round($data['current_income'], 2);

        return $data;
    }

    // 百度今日实时在投
    public function getBaiduInvestingData($params)
    {
        $where[] = ['media_id', '=', 3];
        $totalClickNum = $totalNewUserCount = 0;

        // 链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['id', '=', $params['link_id']];
        }
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
        // 负责人搜索
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        // 公司搜索
        if (!empty($params['company_id'])) {
            // $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id');
            $responsibilityPersonIds = array_column($responsibilityPerson, 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $key1 = config('redis_key.baidu_real_time_investment_create_time') . date('Ymd');
        $key2 = config('redis_key.baidu_real_time_investment_link_user_register_num');

        // 取缓存数据
        if ($timeStamp = $redis->get($key1)) {
        // if (true) {
            $timeStamp = $redis->get($key1);
            $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
            // $total_order_count = $this->linkOrderCount($data);
            //if ($data) {
            $totalClickNum = 0;
            foreach ($data as $key => $item) {
                // 获取点击数
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                $clickNum = $redis->get($redisKey);
                $totalClickNum = $totalClickNum + $clickNum;

                // 获取当日累计注册用户数
                $linkRegisterUserNum = $redis->get($key2 . $item['id']);
                $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
            }
            return [
                'create_time' => date('Y-m-d H:i:s', $timeStamp),
                'total_click_num' => $totalClickNum,
                'total_new_user' => $totalNewUserCount,
                // 'total_order_count' => $total_order_count,
                'data' => $data
            ];
            //}
        }

        $linkData = $this->model->getDataByWhere(['link_switch' => 1, 'media_id' => 3], 'id, video_id, video_detail_id, advertiser_id, responsibility_person_id, rebate, echo_rate,link_type');

        $accessToken = Common::getBaiduAccessToken();

        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $data = $accountIds = $responsibilityPersonIds = [];
        $url = 'https://api.baidu.com/json/feed/v1/ReportFeedService/getRealTimeFeedData';
        $subUserListKey = config('baidu.baidu_sub_user_list');
        $subUserList = $redis->hGetAll($subUserListKey);

        // 
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id']) || empty($subUserList[$value['advertiser_id']])) {
                continue;
            }

            // 获取成本
            $requestData = [
                'header' => [
                    'userName' => $subUserList[$value['advertiser_id']],
                    'accessToken' => $accessToken
                ],
                'body' => [
                    'realTimeRequestType' => [
                        'performanceData' => ['cost'],
                        'startDate' => $startDate,
                        'endDate' => $endDate,
                        'levelOfDetails' => 2,
                        'reportType' => 700,
                        'unitOfTime' => 5
                    ]
                ]
            ];

            $result = Common::_curl($url, $requestData, 'POST', $hearder);
            $result = json_decode($result, true);

            if ($result['header']['desc'] == 'success' && $result['header']['status'] == 0) {
                $value['cost'] = 0;
                if (!empty($result['body']['data'])) {
                    $value['cost'] = round($result['body']['data'][0]['kpis'][0], 2);
                }

                $data[] = $value;
            } else {
                return ['message' => $result['header']['desc'] . '；link_id：' . $value['id']];
            }

            $accountIds[] = $value['advertiser_id'];
            $responsibilityPersonIds[] = $value['responsibility_person_id'];
        }

        $redisUserLinkRegisterData = [];
        if ($data) {
            // 短剧
            $videoIds = array_column($data, 'video_id');
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            $ids = array_column($data, 'id');
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59']]
            ];
            $userInfo = $this->userModel->getBatchDataByWhere($userWhere, 'id, link_id');
            $payData = $this->payRecordModel->getInfo(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd')], 'link_id, uid, total_fee, activation_time');

            $newUids = $newUserPayData = $rechargeNumber = $userData = [];

            if ($userInfo) {

                foreach ($userInfo as $key => $value) {
                    $newUids[] = $value['id'];
                    $redisUserLinkRegisterData[$value['link_id']][] = $value['id'];
                }

                // 当天这个链接上的用户数据
                $links = array_column($userInfo, 'link_id');
                $userData = array_count_values($links);
            }

            $newUserNum = $tencentPayData = [];
            // 当天新用户充值（当期充值）
            $startTime = strtotime(date('Y-m-d'));
            $endTime = strtotime(date('Y-m-d')) + 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }
                // $payResult[$value['link_id']][] = $value['total_fee'];
                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点数据
            $launchAccountData = $this->launchAccountModel->getDataByWhere(['account_id' => $accountIds], 'account_id, rebate');
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            // 获取负责人数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data as $key => $item) {
                $data[$key]['video_name'] = $videos[$item['video_id']];

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值

                // by huangxiaoshan 2023-07-12 当期充值95折扣
                $virtualPayment = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $currentRechargeDiscount = round($currentRecharge * 0.9, 2); // 当期95充值;
                $data[$key]['current_recharge_discount'] = $currentRechargeDiscount;
                // end.

                $data[$key]['current_recovery'] = $item['cost'] == 0 ? 0 : round($currentRecharge / $item['cost'] * 100, 2) . '%'; // 当期回收
                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $data[$key]['conversion_number'] = $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $data[$key]['conversion_cost'] = $newUserNumber == 0 ? 0 : round($item['cost'] / $newUserNumber, 2); // 转化成本

                $data[$key]['fans_cost'] = !empty($userData[$item['id']]) ? round($item['cost'] / $userData[$item['id']]) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = $currentRecharge;

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献

                $userLinkRegisterNum = empty($redisUserLinkRegisterData[$item['id']]) ? 0 : count($redisUserLinkRegisterData[$item['id']]);
                // 转化率
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
                $redis->set($redisKey, $userLinkRegisterNum, 15 * 60);
                if (empty($newUserNumber) || empty($userLinkRegisterNum)) {
                    $data[$key]['conversion_rate'] = '0%';
                } else {
                    $data[$key]['conversion_rate'] = round($newUserNumber / $userLinkRegisterNum * 100, 2) . '%';
                }

                $redis->set($key2 . $item['id'], $userLinkRegisterNum, 15 * 60);
                $data[$key]['media_id'] = 3; // 百度

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } else if (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                unset($data[$key]['rebate']);
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 实际回收
                $data[$key]['actual_cost'] = round($actualCost, 2);

                // by huangxiaoshan 2023-07-12 当期充值95折扣后净利润.
                $data[$key]['current_recharge_profit'] = round($currentRechargeDiscount - $actualCost, 2);
                // end

                // 负责人数据
                $data[$key]['responsibility_person_name'] = $responsibilityPerson[$item['responsibility_person_id']];

                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况
            }
        }

        Db::name('real_time_data_cache')->where(['media_id' => 3])->delete(true);
        $bool = Db::name('real_time_data_cache')->insertAll($data);
        if ($bool) {
            $redis->set($key1, time(), 15 * 60); // 数据产生的时间
        }

        $data = Db::name('real_time_data_cache')->where($where)->order('id', 'desc')->select()->toArray();
        foreach ($data as $item) {

            // 获取点击数
            $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd') . '-' . $item['id'];
            $clickNum = $redis->get($redisKey);
            $totalClickNum = $totalClickNum + $clickNum;

            // 获取当日累计注册用户数
            $linkRegisterUserNum = $redis->get($key2 . $item['id']);
            $totalNewUserCount = $totalNewUserCount + $linkRegisterUserNum;
        }

        $result = [
            'create_time' => date('Y-m-d H:i:s'),
            'total_click_num' => $totalClickNum,
            'total_new_user' => $totalNewUserCount,
            'data' => $data
        ];

        return $result;
    }

    // 获取百度账户列表数据
    public function getBaiduAccountList()
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $key = config('baidu.baidu_sub_user_list');
        $data = $redis->hGetAll($key);
        $returnData = [];
        foreach ($data as $key => $value) {
            $returnData[] = [
                'advertiser_id' => $key,
                'advertiser_name' => $value
            ];
        }
        return $returnData;
    }

    // 按公司统计列表
    public function getByCompanyCountList($params)
    {
        $companyData = $this->companyModel->getDataByWhere(['is_distributor' => 0]);
        $companyIds = array_column($companyData, 'id');

        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $companyIds], 'id, company_id');
        $responsibilityPerson = [];
        foreach ($responsibilityPersonData as $key => $value) {
            $responsibilityPerson[$value['company_id']][] = $value['id'];
            $responsibilityPersonIds[] = $value['id'];
        }

        $companyResult = [];
        foreach ($companyData as $key => $value) {
            $companyResult[] = ['company_id' => $value['id'], 'company_name' => $value['name'], 'responsibility_ids' => $responsibilityPerson[$value['id']]];
        }

        // 投放媒体搜索
        if (!empty($params['media_id'])) {
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds, 'media_id' => $params['media_id']], 'id, responsibility_person_id, media_id');
        } else {
            $linkData = $this->model->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id, responsibility_person_id, media_id');
        }

        $link = [];
        foreach ($linkData as $key => $value) {
            $link[$value['responsibility_person_id']][] = $value['id'];
        }

        foreach ($companyResult as $key => $value) {
            $linkIds = [];
            foreach ($value['responsibility_ids'] as $k => $val) {
                if (!empty($link[$val])) {
                    foreach ($link[$val] as $linkId) {
                        $linkIds[] = $linkId;
                    }
                }
            }

            $companyResult[$key]['link_ids'] = $linkIds;
        }

        $where = [];
        // 时间日期搜索
        if (!empty($params['start_date'])) {
            $startDate = date('Ymd', strtotime($params['start_date']));
            $where[] = ['date', '>=', $startDate];
        }

        if (!empty($params['end_date'])) {
            $endDate = date('Ymd', strtotime($params['end_date']));
            $where[] = ['date', '<=', $endDate];
        }

        // 投放媒体搜索
        if (!empty($params['media_id'])) {
            $where[] = ['platform', '=', $params['media_id']];
        }

        $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, link_id, cost, actual_cost, register_user_num, activation_user_num, current_recharge, total_recharge, recharge_number, conversion_number, virtual_payment');
        $dailyDelivery = [];
        foreach ($dailyDeliveryData as $key => $value) {
            $dailyDelivery[$value['link_id']][] = $value;
        }

        foreach ($companyResult as $key => $value) {

            $companyResult[$key] = [
                'company_id' => $value['company_id'],
                'company_name' => $value['company_name'],
                'cost' => 0,
                'actual_cost' => 0,
                'register_user_num' => 0,
                'activation_user_num' => 0,
                'current_recharge' => 0,
                'total_recharge' => 0,
                'recharge_number' => 0,
                'conversion_number' => 0,
                'virtual_payment' => 0,
                'total_income' => 0
            ];
            $currentRechargeDiscount = 0;

            foreach ($value['link_ids'] as $linkId) {
                if (!empty($dailyDelivery[$linkId])) {
                    foreach ($dailyDelivery[$linkId] as $item) {
                        $companyResult[$key]['cost'] += $item['cost'];
                        $companyResult[$key]['actual_cost'] += $item['actual_cost'];
                        $companyResult[$key]['register_user_num'] += $item['register_user_num'];
                        $companyResult[$key]['activation_user_num'] += $item['activation_user_num'];
                        $companyResult[$key]['current_recharge'] += $item['current_recharge'];
                        if ($item['date'] < 20230821) {
                            $currentRechargeDiscount += $item['current_recharge'] * 0.95;
                            $companyResult[$key]['total_income'] += $item['total_recharge'] * 0.95;
                        } else {
                            $currentRechargeDiscount += $item['current_recharge'] * 0.9;
                            $companyResult[$key]['total_income'] += $item['total_recharge'] * 0.9;
                        }
                        $companyResult[$key]['total_recharge'] += $item['total_recharge'];
                        $companyResult[$key]['recharge_number'] += $item['recharge_number'];
                        $companyResult[$key]['conversion_number'] += $item['conversion_number'];
                        $companyResult[$key]['virtual_payment'] += $item['virtual_payment'];
                    }
                }
            }

            $companyResult[$key]['cost'] = round($companyResult[$key]['cost'], 2);
            $companyResult[$key]['actual_cost'] = round($companyResult[$key]['actual_cost'], 2);
            $companyResult[$key]['current_recharge'] = round($companyResult[$key]['current_recharge'], 2);

            $companyResult[$key]['total_recharge'] = round($companyResult[$key]['total_recharge'], 2);
            // 当期营收 by update huangxiaohshan 2023-07-24
            $currentRechargeDiscount = round($currentRechargeDiscount, 2);
            $companyResult[$key]['current_recharge_discount'] = $currentRechargeDiscount;
            $companyResult[$key]['current_recharge_profit'] = round($companyResult[$key]['total_income'] - $companyResult[$key]['actual_cost'], 2); // 当期利润.
            // end
            $companyResult[$key]['current_recovery'] = empty($companyResult[$key]['actual_cost']) ? '0%' : round($currentRechargeDiscount / $companyResult[$key]['actual_cost'] * 100, 2) . '%';
            $companyResult[$key]['total_recovery'] = empty($companyResult[$key]['actual_cost']) ? '0%' : round($companyResult[$key]['total_income'] / $companyResult[$key]['actual_cost'] * 100, 2) . '%';
            $companyResult[$key]['revenue'] = round($companyResult[$key]['total_recharge'] - $companyResult[$key]['actual_cost'], 2);
            $companyResult[$key]['total_income'] = round($companyResult[$key]['total_income'], 2);
        }
        return $companyResult;
    }

    /**
     * 订单总数，就是推广链接的实时费用花费列表里面的快手，百度，抖音。
     * @param array $data
     * @return int|mixed
     */
    private function linkOrderCount($data = [])
    {
        if ($data) {
            $total_order_count = 0;
            foreach ($data as $key => $val) {
                $total_order_count += (isset($val['order_count']) && $val['order_count']) ? $val['order_count'] : 0;
            }
            return $total_order_count;
        }
        return 0;
    }

    /**
     * 获取操作对象
     * @param $url
     * @return array
     */
    public static function getActionUrlArr($url = null)
    {
        $urlConfigArr = [
            'cps/Video/addConfig' => ['name' => '短剧收费配置','action' => '新增'],
            'cps/Video/editConfig' => ['name' => '短剧收费配置','action' => '编辑'],
            'cps/Recharge/batchSetTemplate' => ['name' => '推广链接-批量设置充值模版','action' => '编辑'],
            'cps/Link/edit' => ['name' => '推广链接','action' => '编辑'],
            'cps/Link/add' => ['name' => '推广链接','action' => '新增'],
            'cps/Video/batchSettingPay' => ['name' => '推广链接-批量设置收费','action' => '编辑'],
            'cps/Back/batchUpdateSet' => ['name' => '推广链接-批量设置回传配置','action' => '编辑'],
            'cps/Recharge/edit' => ['name' => '自定义充值模版','action' => '编辑'],
            'cps/Recharge/add' => ['name' => '自定义充值模版','action' => '新增'],
        ];
        if ($url){
            return $urlConfigArr[$url] ?? [];
        }
        return $urlConfigArr;
    }

    /**
     * 投放操作日志
     * @param $params
     * @return array
     */
    public function operateLog($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        $urls = array_keys(self::getActionUrlArr());
        $where[] = ['url', 'in', $urls];
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        if (!empty($params['responsibility_person_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
        }
        if (!empty($params['official_account_id'])) {
            $where[] = ['official_account_id', '=', $params['official_account_id']];
        }
        if (!empty($params['start_date'])) {
            $startTime = strtotime($params['start_date']);
            $where[] = ['created_at', '>=', $startTime];
        }
        if (!empty($params['end_date'])) {
            $endTime = strtotime($params['end_date']);
            $where[] = ['created_at', '<=', $endTime];
        }
        $data = $this->operateLogModel->getPagingDataByWhere($where, $page, $limit, 'id, official_account_id, responsibility_person_id, url, param, created_at');
        if ($data['data']) {
            foreach ($data['data'] as $key => &$value) {
                $officialAccount = $this->officialAccountModel->getInfoById($value['official_account_id'],'name');
                $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($value['responsibility_person_id'],'name');
                $data['data'][$key]['official_account_name'] = $officialAccount['name'] ?? '';
                $data['data'][$key]['responsibility_person_name'] = $responsibilityPerson['name'] ?? '';
                $data['data'][$key]['operate_object'] = self::getActionUrlArr($value['url'])['name'] ?? '';
                $data['data'][$key]['operate_action'] = self::getActionUrlArr($value['url'])['action'] ?? '';
                $operateDetailArr = [];
                $params = $value['param'] ? json_decode($value['param'],true) : [];
                if (!empty($params)){
                    foreach ($params as $k=>&$v){
                        if (!empty($v)){
                            $tmpStr = '';
                            switch ($value['url']) {
                                case 'cps/Video/addConfig':
                                case 'cps/Video/editConfig':
                                    {
                                        switch ($k){
                                            case 'name':
                                                $tmpStr = '名称';
                                                break;
                                            case 'official_account_id':
                                                $tmpStr = '公众号';
                                                $v = OfficialAccounts::find($v)->value('name') ?? '';
                                                break;
                                            case 'responsibility_person_id':
                                                $tmpStr = '操作人';
                                                $v = ResponsibilityPerson::find($v)->value('name') ?? '';
                                                break;
                                            case 'video_id':
                                                $tmpStr = '短剧';
                                                $v = Videos::find($v)->value('name') ?? '';
                                                break;
                                            case 'sort':
                                                $tmpStr = '开始收费剧集';
                                                break;
                                            case 'pay_amount':
                                                $tmpStr = '收费K币';
                                                break;
                                            case 'status':
                                                $tmpStr = '状态';
                                                $v = $v == 1 ? '已完结' : '未完结';
                                                break;
                                            default:
                                                $tmpStr = $k;
                                                break;
                                        }
                                    }
                                    break;
                                case 'cps/Recharge/batchSetTemplate':
                                    {
                                        switch ($k){
                                            case 'link_ids':
                                                $tmpStr = '链接ids';
                                                break;
                                            case 'recharge_template_id':
                                                $tmpStr = '充值模版';
                                                $v = RechargeTemplate::find($v)->value('name') ?? '';
                                                break;
                                            default:
                                                $tmpStr = $k;
                                                break;
                                        }
                                    }
                                    break;
                                case 'cps/Link/edit':
                                case 'cps/Link/add':
                                case 'cps/Back/batchUpdateSet':
                                    {
                                        switch ($k){
                                            case 'official_account_id':
                                                $tmpStr = '公众号';
                                                $v = OfficialAccounts::find($v)->value('name') ?? '';
                                                break;
                                            case 'url':
                                                $tmpStr = '链接地址';
                                                break;
                                            case 'media_id':
                                                $tmpStr = '媒体';
                                                $mediaArr = [
                                                    1 => '抖音',
                                                    2 => '快手',
                                                    3 => '百度',
                                                    4 => '腾讯',
                                                ];
                                                $v = $mediaArr[$v] ?? '';
                                                break;
                                            case 'link_type':
                                                $tmpStr = '链接类型';
                                                break;
                                            case 'video_id':
                                                $tmpStr = '短剧';
                                                $vData = Videos::find($v);
                                                $v = !empty($vData['name']) ? $vData['name'] : '';
                                                break;
                                            case 'video_detail_id':
                                                $tmpStr = '视频';
                                                $vData = VideoDetails::find($v);
                                                $v = !empty($vData['name']) ? $vData['name'] : '';
                                                break;
                                            case 'is_open':
                                                $tmpStr = '回传开关';
                                                $v = $v == 1 ? '开' : '关';
                                                break;
                                            case 'designated_amount_echo':
                                                $tmpStr = '指定金额回传';
                                                $strArr = [];
                                                $arr = json_decode($v,true);
                                                foreach ($arr as $a){
                                                    $str = '';
                                                    foreach ($a as $kv=>$vItem){
                                                        if (!empty($vItem)){
                                                            switch ($kv){
                                                                case 'price':
                                                                    $str.= '金额:'.$vItem.'、';
                                                                    break;
                                                                case 'rate':
                                                                    $str.= '回传率:'.$vItem.'、';
                                                                    break;
                                                                case 'update_time':
                                                                    $str.= '更新时间:'.date('Y-m-d H:i:s',$vItem);
                                                                    break;
                                                            }
                                                        }
                                                    }
                                                    $strArr[] = $str;
                                                }
                                                $v = join(' ; ',$strArr);
                                                break;
                                            case 'design_switch':
                                                $tmpStr = '指定金额开关';
                                                $v = $v == 1 ? '开' : '关';
                                                break;
                                            case 'echo_rate':
                                                $tmpStr = '回传率';
                                                break;
                                            case 'edit_echo_rate_time':
                                                $tmpStr = '最近一次修改回传率的时间';
                                                break;
                                            case 'echo_rule_config_id':
                                                $tmpStr = '回传规则配置id';
                                                break;
                                            case 'recharge_template_id':
                                                $tmpStr = '充值模板';
                                                $vData = RechargeTemplate::find($v);
                                                if (empty($vData)) {
                                                    $vData = CustomRechargeTemplate::find($v);
                                                }
                                                $v = !empty($vData) ? $vData['name'] : '';
                                                break;
                                            case 'video_pay_setting_id':
                                                $tmpStr = '自定义短剧收费设置ID';
                                                break;
                                            case 'subject_id':
                                                $tmpStr = '主体ID';
                                                break;
                                            case 'advertiser_id':
                                                $tmpStr = '广告账户id';
                                                break;
                                            case 'is_capitalization':
                                                $tmpStr = '是否是资产化';
                                                break;
                                            case 'token':
                                                $tmpStr = '百度投放token';
                                                break;
                                            case 'version':
                                                $tmpStr = '抖音投放版本';
                                                break;
                                            case 'project_id':
                                                $tmpStr = '抖音广告项目ID';
                                                break;
                                            case 'rebate':
                                                $tmpStr = '返点';
                                                break;
                                            case 'recharge_price':
                                                $tmpStr = '充值金额';
                                                break;
                                            case 'link_switch':
                                                $tmpStr = '是否开启投放开关';
                                                $v = $v == 1 ? '开' : '关';
                                                break;
                                            case 'spend':
                                                $tmpStr = '花费金额';
                                                break;
                                            case 'responsibility_person_id':
                                                $tmpStr = '负责人id';
                                                break;
                                            case 'external_link':
                                                $tmpStr = '投放链接';
                                                break;
                                            case 'is_open_low_recharge_not_echo':
                                                $tmpStr = '是否开启低充值不回传';
                                                break;
                                            case 'not_echo_recharge_price':
                                                $tmpStr = '不回传充值金额';
                                                break;
                                            case 'remark':
                                                $tmpStr = '备注';
                                                break;
                                            case 'release_start_time':
                                                $tmpStr = '投放开始时间';
                                                $v = date('Y-m-d H:i:s',$v);
                                                break;
                                            case 'release_end_time':
                                                $tmpStr = '投放关闭时间';
                                                $v = date('Y-m-d H:i:s',$v);
                                                break;
                                            case 'link_count':
                                                $tmpStr = '链接数量';
                                                break;
                                            default:
                                                $tmpStr = $k;
                                                break;
                                        }
                                    }
                                    break;
                                case 'cps/Video/batchSettingPay':
                                    {
                                        switch ($k){
                                            case 'link_ids':
                                                $tmpStr = '链接ids';
                                                break;
                                            case 'video_id':
                                                $tmpStr = '视频';
                                                $v = Videos::find($v)->value('name') ?? '';
                                                break;
                                            case 'video_pay_setting_id':
                                                $tmpStr = 'ly_video_pay_config表id';
                                                break;
                                            default:
                                                $tmpStr = $k;
                                                break;
                                        }
                                    }
                                    break;
                                case 'cps/Recharge/add':
                                case 'cps/Recharge/edit':
                                    {
                                        switch ($k){
                                            case 'name':
                                                $tmpStr = '名称';
                                                break;
                                            case 'type':
                                                $tmpStr = '类型';
                                                $typeArr = [
                                                    1 => '低充',
                                                    2 => '中充',
                                                    3 => '高充',
                                                ];
                                                $v = $typeArr[$v] ?? '';
                                                break;
                                            case 'recharged_content':
                                                $tmpStr = '已充值';
                                                $strArr = [];
                                                $arr = json_decode($v,true);
                                                foreach ($arr as $a){
                                                    $str = '';
                                                    foreach ($a as $kv=>$vItem){
                                                        switch ($kv){
                                                            case 'id':
                                                                $str.= 'id:'.$vItem.'、';
                                                                break;
                                                            case 'name':
                                                                $str.= '名称:'.$vItem.'、';
                                                                break;
                                                            case 'label':
                                                                $str.= '标签:'.$vItem.'、';
                                                                break;
                                                            case 'original_currency':
                                                                $str.= '充值K币:'.$vItem.'、';
                                                                break;
                                                            case 'recharge_price':
                                                                $str.= '充值金额:'.$vItem.'、';
                                                                break;
                                                            case 'send_currency':
                                                                $str.= '赠送K币:'.$vItem.'、';
                                                                break;
                                                            case 'sum_currency':
                                                                $str.= '总K币:'.$vItem.'、';
                                                                break;
                                                            case 'send_title':
                                                                $str.= '赠送标题:'.$vItem.'、';
                                                                break;
                                                            case 'checkedName':
                                                                $str.=  $vItem == 'recharged' ? '已充值配置' : '未充值配置';
                                                                $str.=  '、';
                                                                break;
                                                            case 'checked':
                                                                $str.=  $vItem == 'checked' ? '默认选中' : '';
                                                                break;
                                                        }
                                                    }
                                                    $strArr[] = $str;
                                                }
                                                $v = join(' ; ',$strArr);
                                                break;
                                            case 'not_recharged_content':
                                                $tmpStr = '未充值';
                                                $strArr = [];
                                                $arr = json_decode($v,true);
                                                foreach ($arr as $a){
                                                    $str = '';
                                                    foreach ($a as $kv=>$vItem){
                                                        switch ($kv){
                                                            case 'id':
                                                                $str.= 'id:'.$vItem.'、';
                                                                break;
                                                            case 'name':
                                                                $str.= '名称:'.$vItem.'、';
                                                                break;
                                                            case 'label':
                                                                $str.= '标签:'.$vItem.'、';
                                                                break;
                                                            case 'original_currency':
                                                                $str.= '充值K币:'.$vItem.'、';
                                                                break;
                                                            case 'recharge_price':
                                                                $str.= '充值金额:'.$vItem.'、';
                                                                break;
                                                            case 'send_currency':
                                                                $str.= '赠送K币:'.$vItem.'、';
                                                                break;
                                                            case 'sum_currency':
                                                                $str.= '总K币:'.$vItem.'、';
                                                                break;
                                                            case 'send_title':
                                                                $str.= '赠送标题:'.$vItem.'、';
                                                                break;
                                                            case 'checkedName':
                                                                $str.=  $vItem == 'recharged' ? '已充值配置' : '未充值配置';
                                                                $str.=  '、';
                                                                break;
                                                            case 'checked':
                                                                $str.=  $vItem == 'checked' ? '默认选中' : '';
                                                                break;
                                                        }
                                                    }
                                                    $strArr[] = $str;
                                                }
                                                $v = join(' ; ',$strArr);
                                                break;
                                            default:
                                                $tmpStr = $k;
                                                break;
                                        }
                                    }
                                    break;
                            }
                            $operateDetailArr[] = $tmpStr.':'.$v;
                        }
                    }
                }
                $data['data'][$key]['operate_detail_arr'] = $operateDetailArr;
            }
        }
        return $data;
    }

    // 操作人下拉列表
    public function getOperateSelectList()
    {
        $whereOr = [
            ['pid', '>', 0],
            ['is_distributor', '=', 1],
        ];
        return $this->responsibilityPersonModel->whereOr($whereOr)->field('id, name')->select();
    }
}
